2017-11-02 1 views
-1

tcpclient와의 연결이 이루어지기 전까지는 작동하지 않는 Windows 양식이 있습니다. 그런 다음 제대로 작동하지 않습니다 (정지 상태, 정지 상태). Winform + TCPListener가 제대로로드되지 않습니다.

은 TCPListener 코드입니다 :

using System; 
using System.Drawing; 
using System.IO; 
using System.Net; 
using System.Net.Sockets; 
using System.Security.Cryptography; 
using System.Text; 
using System.Windows.Forms; 
namespace ServerChatGUI 
{ 
public partial class Form1 : Form 
{ 
    public Timer timer1; 
    public TcpListener myList = null; 

    public string EncryptionKey = GetHashedKey("Alexandros"); 

    public Form1() 
    { 
     InitializeComponent(); 
     try 
     { 
      IPAddress ipAd = IPAddress.Parse("172.17.1.241"); 
      // use local m/c IP address, and 
      // use the same in the client 

      /* Initializes the Listener */ 
      myList = new TcpListener(ipAd, 8001); 

      /* Start Listeneting at the specified port */ 
      myList.Start(); 


      Socket s = myList.AcceptSocket(); 
      this.Show(); 

      chatDisplay_txtbox.AppendText("Connection accepted from " + s.RemoteEndPoint + "\n"); 
      connection_lbl.Text = "Connected"; 
      connection_lbl.ForeColor = Color.Green; 


      //InitTimer(); 
     } 

     catch (Exception e) 
     { 
      Console.WriteLine("Error..... " + e.ToString()); 
     } 


    } 

    public static string GetHashedKey(string text) 
    { 
     byte[] bytes = Encoding.UTF8.GetBytes(text); 
     SHA256Managed hashstring = new SHA256Managed(); 
     byte[] hash = hashstring.ComputeHash(bytes); 
     string hashString = string.Empty; 
     int cntr = 0; 
     foreach (byte x in hash) 
     { 
      if (cntr == 1) 
      { 
       cntr = 0; 
      } 
      else 
      { 
       hashString += String.Format("{0:x2}", x); 
       cntr++; 
      } 
     } 
     return hashString; 
    } 

    //Encrypting a string 
    public static string TxtEncrypt(string inText, string key) 
    { 
     byte[] bytesBuff = Encoding.UTF8.GetBytes(inText); 
     using (Aes aes = Aes.Create()) 
     { 
      Rfc2898DeriveBytes crypto = new Rfc2898DeriveBytes(key, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); 
      aes.Key = crypto.GetBytes(32); 
      aes.IV = crypto.GetBytes(16); 
      using (MemoryStream mStream = new MemoryStream()) 
      { 
       using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateEncryptor(), CryptoStreamMode.Write)) 
       { 
        cStream.Write(bytesBuff, 0, bytesBuff.Length); 
        cStream.Close(); 
       } 
       inText = Convert.ToBase64String(mStream.ToArray()); 
      } 
     } 
     return inText; 
    } 

    //Decrypting a string 
    public static string TxtDecrypt(string cryptTxt, string key) 
    { 
     cryptTxt = cryptTxt.Replace(" ", "+"); 
     cryptTxt = cryptTxt.Replace("\0", ""); 
     byte[] bytesBuff = Convert.FromBase64String(cryptTxt); 
     using (Aes aes = Aes.Create()) 
     { 
      Rfc2898DeriveBytes crypto = new Rfc2898DeriveBytes(key, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); 
      aes.Key = crypto.GetBytes(32); 
      aes.IV = crypto.GetBytes(16); 
      using (MemoryStream mStream = new MemoryStream()) 
      { 
       using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateDecryptor(), CryptoStreamMode.Write)) 
       { 
        cStream.Write(bytesBuff, 0, bytesBuff.Length); 
        cStream.Close(); 
       } 
       cryptTxt = Encoding.UTF8.GetString(mStream.ToArray()); 
      } 
     } 
     return cryptTxt; 
    } 


    private void button1_Click(object sender, EventArgs e) 
    { 
     Socket s = myList.AcceptSocket(); 
     chatDisplay_txtbox.AppendText("Me:\t "); 
     chatDisplay_txtbox.AppendText(inMessage_txtbox.Text + "\n"); 


     String str = TxtEncrypt(inMessage_txtbox.Text, EncryptionKey); 
     s.Send(Encoding.UTF8.GetBytes(str)); 

    } 

    public void InitTimer() 
    { 
     timer1 = new Timer(); 
     timer1.Tick += new EventHandler(timer1_Tick); 
     timer1.Interval = 200; // in miliseconds 
     timer1.Start(); 
    } 

    private void timer1_Tick(object sender, EventArgs e) 
    { 
     Socket s = myList.AcceptSocket(); 
     if (s.Available > 0) 
     { 
      byte[] b = new byte[s.ReceiveBufferSize]; 
      int k = s.Receive(b); 
      string msg = ""; 
      chatDisplay_txtbox.AppendText("Other:\t"); 
      for (int i = 0; i < k; i++) 
      { 
       msg += Convert.ToChar(b[i]); 
      } 
      chatDisplay_txtbox.AppendText(TxtDecrypt(msg, EncryptionKey) + "\n"); 
     } 
    } 
} 
} 

그리고 이것은하여 TCP Client에 대한 코드 (이 하나가 작동하지 않습니다)입니다 : 내가 할 수있었습니다 무엇을 위해

using System; 
using System.Drawing; 
using System.IO; 
using System.Net.Sockets; 
using System.Security.Cryptography; 
using System.Text; 
using System.Windows.Forms; 
namespace ChatClientGUI 
{ 
public partial class Form1 : Form 
{ 
    public string EncryptionKey = GetHashedKey("Alexandros"); 
    public TcpClient tcpclnt = null; 
    public bool cntrl = false; 
    public Timer timer1; 
    public Form1() 
    { 
     InitializeComponent(); 
     try 
     { 
      tcpclnt = new TcpClient(); 
      chatDisplayer_txtbox.AppendText("this is the beginning of your chat\n"); 
      tcpclnt.Connect("172.17.1.241", 8001); 
      // use the ipaddress as in the server program 



      displayConnection_lbl.Text = "Connected"; 
      displayConnection_lbl.ForeColor = Color.Green; 

      InitTimer(); 
     } 
     catch (Exception e) 
     { 
      Console.WriteLine("Error..... " + e.ToString()); 
     } 

    } 

    public static string GetHashedKey(string text) 
    { 
     byte[] bytes = Encoding.UTF8.GetBytes(text); 
     SHA256Managed hashstring = new SHA256Managed(); 
     byte[] hash = hashstring.ComputeHash(bytes); 
     string hashString = string.Empty; 
     int cntr = 0; 
     foreach (byte x in hash) 
     { 
      if (cntr == 1) 
      { 
       cntr = 0; 
      } 
      else 
      { 
       hashString += String.Format("{0:x2}", x); 
       cntr++; 
      } 
     } 
     return hashString; 
    } 

    //Encrypting a string 
    public static string TxtEncrypt(string inText, string key) 
    { 
     byte[] bytesBuff = Encoding.UTF8.GetBytes(inText); 
     using (Aes aes = Aes.Create()) 
     { 
      Rfc2898DeriveBytes crypto = new Rfc2898DeriveBytes(key, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); 
      aes.Key = crypto.GetBytes(32); 
      aes.IV = crypto.GetBytes(16); 
      using (MemoryStream mStream = new MemoryStream()) 
      { 
       using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateEncryptor(), CryptoStreamMode.Write)) 
       { 
        cStream.Write(bytesBuff, 0, bytesBuff.Length); 
        cStream.Close(); 
       } 
       inText = Convert.ToBase64String(mStream.ToArray()); 
      } 
     } 
     return inText; 
    } 

    //Decrypting a string 
    public static string TxtDecrypt(string cryptTxt, string key) 
    { 
     cryptTxt = cryptTxt.Replace(" ", "+"); 
     byte[] bytesBuff = Convert.FromBase64String(cryptTxt); 
     using (Aes aes = Aes.Create()) 
     { 
      Rfc2898DeriveBytes crypto = new Rfc2898DeriveBytes(key, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); 
      aes.Key = crypto.GetBytes(32); 
      aes.IV = crypto.GetBytes(16); 
      using (MemoryStream mStream = new MemoryStream()) 
      { 
       using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateDecryptor(), CryptoStreamMode.Write)) 
       { 
        cStream.Write(bytesBuff, 0, bytesBuff.Length); 
        cStream.Close(); 
       } 
       cryptTxt = Encoding.UTF8.GetString(mStream.ToArray()); 
      } 
     } 
     return cryptTxt; 
    } 

    private void SendMessage_btn_Click(object sender, EventArgs e) 
    { 
     chatDisplayer_txtbox.AppendText("Me:\t "); 
     chatDisplayer_txtbox.AppendText(inMessage_txtbox.Text + "\n"); 

     String str = TxtEncrypt(inMessage_txtbox.Text, EncryptionKey); 
     Stream stm = tcpclnt.GetStream(); 

     byte[] ba = Encoding.UTF8.GetBytes(str); 

     stm.Write(ba, 0, ba.Length); 
     cntrl = true; 
    } 


    public void InitTimer() 
    { 
     timer1 = new Timer(); 
     timer1.Tick += new EventHandler(timer1_Tick); 
     timer1.Interval = 200; // in miliseconds 
     timer1.Start(); 
    } 

    private void timer1_Tick(object sender, EventArgs e) 
    { 
     if (tcpclnt.Available > 0) 
     { 
      Stream stm = tcpclnt.GetStream(); 

      byte[] bb = new byte[tcpclnt.ReceiveBufferSize]; 

      int k = stm.Read(bb, 0, tcpclnt.ReceiveBufferSize); 
      string msg = ""; 
      chatDisplayer_txtbox.AppendText("Other:\t"); 
      for (int i = 0; i < k; i++) 
      { 
       msg += Convert.ToChar(bb[i]); 
      } 
      chatDisplayer_txtbox.AppendText(TxtDecrypt(msg, EncryptionKey) + "\n"); ; 
     } 
    } 

} 
} 

추론한다. 사실 일단 멈 추면 타이머와 관련이있는 것처럼 보이지만 동일한 타이머는 TCP 클라이언트에서 작동한다.

나는 정말로 길을 잃었고, 내가 실수를했고 왜 그랬는지 이해하고 싶다. 아무도 왜 작동하지 않는지 이해할 수 있습니까?

+0

메인 (UI) 스레드에서 모든 작업을 수행하므로 응용 프로그램이 정지됩니다. 비동기 작동 및 스레드에 대해 읽으십시오. –

+0

비동기에 대해 읽었지만 실제로 사용하지는 않는다는 것을 이해하지 못합니다. 또한 클라이언트를 위해 일했습니다. 왜 청취자에게는 효과가 없을까요? –

+0

GUI 폼 ctors 또는 이벤트 핸들러에서 accept()와 같은 블로킹 호출을하지 마십시오. –

답변

0
using System; 
using System.Drawing; 
using System.IO; 
using System.Net; 
using System.Net.Sockets; 
using System.Security.Cryptography; 
using System.Text; 
using System.Windows.Forms; 
namespace ServerChatGUI 
{ 
public partial class Form1 : Form 
{ 
    public static TcpListener myList = null; 
    public static Socket s = null; 
    public static string EncryptionKey = GetHashedKey("Alexandros"); 
    public static TextBox chatBox = null; 

    public Form1() 
    { 
     InitializeComponent(); 
     try 
     { 
      chatBox = chatDisplay_txtbox; 
      IPAddress ipAd = IPAddress.Parse("192.168.1.12"); 
      // use local m/c IP address, and 
      // use the same in the client 

      /* Initializes the Listener */ 
      myList = new TcpListener(ipAd, 8001); 

      /* Start Listeneting at the specified port */ 
      myList.Start(); 

      s = myList.AcceptSocket(); 

      chatDisplay_txtbox.AppendText("Connection accepted from " + s.RemoteEndPoint + "\n"); 
      connection_lbl.Text = "Connected"; 
      connection_lbl.ForeColor = Color.Green; 

      System.Threading.Timer t = new System.Threading.Timer(TimerCallback, null, 0, 2000); 
     } 
     catch (Exception e) 
     { 
      Console.WriteLine("Error..... " + e.ToString()); 
     } 
    } 

    public static string GetHashedKey(string text) 
    { 
     byte[] bytes = Encoding.UTF8.GetBytes(text); 
     SHA256Managed hashstring = new SHA256Managed(); 
     byte[] hash = hashstring.ComputeHash(bytes); 
     string hashString = string.Empty; 
     int cntr = 0; 
     foreach (byte x in hash) 
     { 
      if (cntr == 1) 
      { 
       cntr = 0; 
      } 
      else 
      { 
       hashString += String.Format("{0:x2}", x); 
       cntr++; 
      } 
     } 
     return hashString; 
    } 

    //Encrypting a string 
    public static string TxtEncrypt(string inText, string key) 
    { 
     byte[] bytesBuff = Encoding.UTF8.GetBytes(inText); 
     using (Aes aes = Aes.Create()) 
     { 
      Rfc2898DeriveBytes crypto = new Rfc2898DeriveBytes(key, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); 
      aes.Key = crypto.GetBytes(32); 
      aes.IV = crypto.GetBytes(16); 
      using (MemoryStream mStream = new MemoryStream()) 
      { 
       using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateEncryptor(), CryptoStreamMode.Write)) 
       { 
        cStream.Write(bytesBuff, 0, bytesBuff.Length); 
        cStream.Close(); 
       } 
       inText = Convert.ToBase64String(mStream.ToArray()); 
      } 
     } 
     return inText; 
    } 

    //Decrypting a string 
    public static string TxtDecrypt(string cryptTxt, string key) 
    { 
     cryptTxt = cryptTxt.Replace(" ", "+"); 
     cryptTxt = cryptTxt.Replace("\0", ""); 
     byte[] bytesBuff = Convert.FromBase64String(cryptTxt); 
     using (Aes aes = Aes.Create()) 
     { 
      Rfc2898DeriveBytes crypto = new Rfc2898DeriveBytes(key, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); 
      aes.Key = crypto.GetBytes(32); 
      aes.IV = crypto.GetBytes(16); 
      using (MemoryStream mStream = new MemoryStream()) 
      { 
       using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateDecryptor(), CryptoStreamMode.Write)) 
       { 
        cStream.Write(bytesBuff, 0, bytesBuff.Length); 
        cStream.Close(); 
       } 
       cryptTxt = Encoding.UTF8.GetString(mStream.ToArray()); 
      } 
     } 
     return cryptTxt; 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     chatDisplay_txtbox.AppendText("Me:\t "); 
     chatDisplay_txtbox.AppendText(inMessage_txtbox.Text + "\n"); 

     String str = TxtEncrypt(inMessage_txtbox.Text, EncryptionKey); 
     s.Send(Encoding.UTF8.GetBytes(str)); 
     GC.Collect(); 
    } 

    private void TimerCallback(Object o) 
    { 
     if (s.ReceiveBufferSize > 0) 
     { 
      byte[] b = new byte[s.ReceiveBufferSize]; 
      int k = s.Receive(b); 
      string msg = ""; 
      chatDisplay_txtbox.Invoke(new Action(() => chatDisplay_txtbox.AppendText("Other:\t"))); 
      for (int i = 0; i < k; i++) 
      { 
       msg += Convert.ToChar(b[i]); 
      } 
      chatDisplay_txtbox.Invoke(new Action(() => chatDisplay_txtbox.AppendText(TxtDecrypt(msg, EncryptionKey) + "\n"))); 
      GC.Collect(); 
     } 
    } 
    } 
} 

이 코드는 제대로 작동합니다. 그 증거는 타이머에 있었다.

관련 문제