2012-12-24 196 views
1

我有UDP客戶端聊天,它將消息發送到服務器並獲取響應。我有兩個線程,一個用於發送,一個用於接收消息。我用ReceiveFrom()方法得到異常:「在執行此操作之前,您必須調用綁定方法」。但這是一個客戶,我不想束縛任何東西。例如這個客戶端工作正常:udp客戶端綁定

byte[] data = new byte[30]; 
    string input, stringData; 
    IPEndPoint servIPEP = new IPEndPoint(
      IPAddress.Parse("127.0.0.1"), 9050); 
    EndPoint servEP = (EndPoint)servIPEP; 
    Socket client = new Socket(AddressFamily.InterNetwork, 
      SocketType.Dgram, ProtocolType.Udp); 
    string welcome = "Hello, are you there?"; 
    data = Encoding.ASCII.GetBytes(welcome); 
    client.SendTo(data, data.Length, SocketFlags.None, servEP); 
    data = new byte[30]; 
    int recv = client.ReceiveFrom(data, ref servEP); //works fine! 

沒有綁定接收。但是,當我創建兩個線程錯誤拋出:

public ChatClient() 
     { 
      clientSock = new Socket(AddressFamily.InterNetwork, 
           SocketType.Dgram, ProtocolType.Udp); 
      servIPEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 32000); 
      servEP = (EndPoint)servIPEP; 
     } 

     public void ReceiveThread() 
     { 
      Thread receiveThread = new Thread(new ThreadStart(ReceiveData)); 
      receiveThread.Start(); 
     } 

     public void ReceiveData() 
     { 
      while(true){ 
       clientSock.ReceiveFrom(buf, ref servEP); //Here I get ERROR 
       string msg = Encoding.ASCII.GetString(buf).Trim(); 
       Console.WriteLine("New message: {0}",msg); 
       } 

     } 

     public void SendThread() 
     { 
      Thread sendThread = new Thread(new ThreadStart(SendData)); 
      sendThread.Start(); 
     } 

     public void SendData() 
     { 
      while (true) 
      { 
       Console.WriteLine("Enter message to send: "); 
       string msg = Console.ReadLine(); 
       buf = Encoding.UTF8.GetBytes(msg); 
       clientSock.SendTo(buf, servEP); 
      } 
     } 
    } 


    static void Main(string[] args) 
    { 

     ChatClient client = new ChatClient(); 
     client.SendThread(); 
     client.ReceiveThread(); 
    } 
} 

謝謝你的時間。

+0

我發現它只有在SendTo()是第一個時纔有效,否則當ReceiveFrom()是第一個時它不起作用。有人可以解釋爲什麼它只是這樣工作? –

回答

2

很明顯,SendTo()會執行隱式綁定,而ReceiveFrom()不會。

開始接收沒有事先綁定,至少設置您通過接收的端口號沒有什麼意義。否則,你會如何獲得任何數據?

+0

謝謝,我不知道SendTo()做了隱式綁定,現在它有意義:) –