我有UDP客户端聊天,它将消息发送到服务器并获取响应。我有两个线程,一个用于发送,一个用于接收消息。我使用ReceiveFrom()方法获得异常:“在执行此操作之前必须调用Bind方法”。但这是一个客户端,我不想绑定任何东西。例如,这个客户端工作正常:
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 :(得分:2)
显然,SendTo()执行隐式绑定,而ReceiveFrom()则不执行。
在没有先前绑定的情况下开始接收至少设置您正在接收的端口号没有多大意义。否则你希望获得任何数据?