服务端ip:192.168.1.214。客户端ip:192.168.1.30
客户端代码public static void ReceiveStart(string localip, string localPort)
{
try
{
//创建接受套接字
IPAddress localIP = IPAddress.Parse(localip);
IPEndPoint localIPEndPoint = new IPEndPoint(localIP, int.Parse(localPort));
receiveUdpClient = new UdpClient(localIPEndPoint);
//启动接受线程
Thread threadReceive = new Thread(ReceiveMessages);
threadReceive.IsBackground = true;
threadReceive.Start();
}
catch (Exception ex)
{
MessageBox.Show("错误类型:"+ex.ToString());
}
}
private static void ReceiveMessages()
{
IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, 0);
while (true)
{
try
{
//关闭receiveUdpClient时此句会产生异常
byte[] receiveBytes = receiveUdpClient.Receive(ref remoteIPEndPoint);
/*for (int i = 0; i < receiveBytes.Length; i++)
{
ShwMsgForView.ShwMsgforView(listBox, string.Format("{0}[{1}]", remoteIPEndPoint, receiveBytes[i].ToString()));
}*/
// string message = Encoding.Unicode.GetString(receiveBytes, 0, receiveBytes.Length);
string message = Encoding.ASCII.GetString(receiveBytes, 0, receiveBytes.Length);
//显示接受到的消息内容
//ShwMsgForView.ShwMsgforView(listBox, string.Format("{0}[{1}]", remoteIPEndPoint, message))
label_dis.Text = message;
}
catch
{
break;
}
}
}
然后我用一个button调用他,输入ip是192.168.1.30,port使用的是8099.检测port口没有被占用。打开程序后点击button调用报错:socket的问题,说是在其上下文中该地址无效。我查了下网上的解答,说是要配置路由,但是路由是公用的我不好其配置。。。有没有其他解决方法。