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();
}
}
謝謝你的時間。
我發現它只有在SendTo()是第一個時纔有效,否則當ReceiveFrom()是第一個時它不起作用。有人可以解釋爲什麼它只是這樣工作? –