socket 通信远程主机强迫关闭了一个现有的连接。急!!!在线等。
我最近写了一个局域网通信的程序, 用到了多线程和socket来传输文件、发送消息,主服务器的线程中有一个UDP广播, 每隔三秒向局域网内广播一次,当有重服务器上线时,向主服务器注册。 主服务器还可以控制从服务器, 向其发送消息, 但是, 问题出现了, 主服务器发送的消息,有些时候从服务器能收到, 有些时候就抛出异常 “远程主机强迫关闭了一个现有的连接。”这是什么问题,应该怎么解决啊。
UDP代码:
public void sendUdp() { string str = "I'm running"; UdpClient udp = new UdpClient(2525); try { while (true) { IPAddress ipAdd = IPAddress.Parse("255.255.255.255"); IPEndPoint end = new IPEndPoint(ipAdd, 2020); try { byte[] sendByte = Encoding.Unicode.GetBytes(str); udp.Send(sendByte, sendByte.Length, end); } catch (Exception) { throw; } Thread.Sleep(3000); } } catch (Exception e) { MessageBox.Show(e.Message); throw; } }
public void sendTcp(string ipAddress,string str) { IPAddress ip = IPAddress.Parse(ipAddress); IPEndPoint ipep = new IPEndPoint(ip, 2025); //创建套接字 Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //连接到发送端 try { client.Connect(ipep); } catch (Exception) { MessageBox.Show("指定的从服务器已意外关闭, 链接不上"); } if (client.Connected) { try { this.SendVarData(client, Encoding.Unicode.GetBytes(str)); } catch (Exception) { MessageBox.Show("传输文件失败!"); throw; } public static int SendVarData(Socket s, byte[] data) { int total = 0; int size = data.Length; int dataleft = size; int sent; byte[] datasize = new byte[4]; datasize = BitConverter.GetBytes(size); sent = s.Send(datasize); while (total < size) { sent = s.Send(data, total, dataleft, SocketFlags.None); total += sent; dataleft -= sent; } return total; }