2014-03-13 186 views
2

我正在尝试使用聊天应用程序,并且我正在使用tcp套接字和线程化问题是如何等待命令并发送命令时间同一插座我如何发送和接收同一端口上同时使用套接字

public void GetTextFather() 
    { 
     string Command = ""; 
     string text = ""; 
     while (Command == "") 
      Command = Functions.serverrecievetext(ip, port); 

     if (Command == "Text") 
     { 
      while (text == "") 
       text = Functions.serverrecievetext(ip, port); 
      if (text != "") 
      { 

       listBox1.Invoke((MethodInvoker)delegate { this.listBox1.Items.Add(name + ":" + text); }); 
       Thread t = new Thread(GetTextFather); 
       t.Start(); 
      } 

     } 
     if (Command == "Typing") 
     { 
      label1.Invoke((MethodInvoker)delegate { label1.Visible = true; }); 
      Thread t = new Thread(GetTextFather); 
      t.Start(); 
     } 
     if (Command == "NotTyping") 
     { 
      label1.Invoke((MethodInvoker)delegate { label1.Visible = false; }); 
      Thread t = new Thread(GetTextFather); 
      t.Start(); 
     } 

    } 

发送按钮点击

private void button1_Click(object sender, EventArgs e) 
    {string text=textBox1.Text; 
    listBox1.Items.Add("You:" + text); 
    if (text.Length != 0) 
    { 
     if (!flag) 
     {Functions.ClientSendTextPortsixty("Text", port); 
      Functions.ClientSendTextPortsixty(text, port); 

     } 
     else 
     {Functions.ServerSendbyip("Text", ip, port); 
      Functions.ServerSendbyip(text, ip, port); 

     } 
    } 
    textBox1.Text = ""; 
    } 

函数发送简单,通过socket发送文本和接收得到一个文本。 我有GetTextSon()一样GetTextFather ,如果您需要任何更多的信息仅低于

回答

0

也许我没有正确认识这个问题发表评论,但是这个代码在过去一直为我工作。我要去忽略UI片,和只写套接字代码(这是从内存中,而应该是八九不离十):

public class ChatClient 
{ 
    public event Action<String> MessageRecieved; 

    private TcpClient socket; 
    public ChatClient(String host, int port) 
    { 
     socket = new TcpClient(host, port); 
     Thread listenThread = new Thread(ReadThread); 
     listenThread.Start(); 
    } 

    private void ReadThread() 
    { 
     NetworkStream netStream = socket.GetStream(); 
     while (socket.Connected) 
     { 
      //Read however you want, something like: 
      // Reads NetworkStream into a byte buffer. 
      byte[] bytes = new byte[socket.ReceiveBufferSize]; 

      // Read can return anything from 0 to numBytesToRead. 
      // This method blocks until at least one byte is read. 
      netStream.Read (bytes, 0, (int)socket.ReceiveBufferSize); 

      // Returns the data received from the host to the console. 
      MessageRecieved(Encoding.UTF8.GetString (bytes)); 
     } 
    } 

    public void SendMessage(string msg) 
    { 
     NetworkStream netStream = socket.GetStream(); 
     Byte[] sendBytes = Encoding.UTF8.GetBytes (msg); 
     netStream.Write (sendBytes, 0, sendBytes.Length); 
    } 
} 

现在,解决差异化的问题,我拆我的所有邮件分为“命令”和“数据”两部分。例如,如果您要发送一个“踢用户”命令:

Send: "KickUser:bob" 
Recieve: "UserKicked:bob" 

来自另一个用户的聊天消息会是这样的:

Recieve: "ChatMessage:Hi" 

谁要使用客户端只是监听的MessageRecieved事件并适当地解析消息,引发用户界面更新所需的任何事件。

让我知道你在想什么!