问题描述
- 设备连接服务器,从代码上看是同时产生连个socket进行通信吗?有何影响?
-
设备连接服务器端有两个端口,是同时建立socket通信吗?两个socket连接同时产生吗?如果其中一个端口发生阻塞,设备与服务器连接就全部发生再另外一个socket连接上吗?代码如下:
CheckServerConnect(Global.Hitems1stIP, Global.Hitems1stPort, lblHiTems1stStatus);
CheckServerConnect(Global.Hitems2ndIP, Global.Hitems2ndPort, lblHiTems2ndStatus);#endregion #region CheckServerConnect private void CheckServerConnect(string ip, int port, Label lbl) { Thread thread = new Thread(new ThreadStart(delegate() { DoCheck(ip, port, lbl); })); thread.Start(); } private void DoCheck(string ip, int port, Label lbl) { IPEndPoint ipep = null; Socket socket = null; try { ipep = new IPEndPoint(IPAddress.Parse(ip), port); socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Connect(ipep); SetLabel(lbl, Color.Blue, "Connected"); } catch //(Exception e) { SetLabel(lbl, Color.Red, "Disconnected"); } finally { if (ipep != null) { ipep = null; } if (socket != null) { socket.Close(); socket = null; } } } delegate void SetLabelInvoker(Label lbl, Color backColor, string message); private void SetLabel(Label lbl, Color backColor, string message) { try { if (lbl.InvokeRequired) { lbl.BeginInvoke(new SetLabelInvoker(SetLabel), lbl, backColor, message); return; } lbl.BackColor = backColor; lbl.Text = message; } catch { } } #endregion
时间: 2025-01-03 08:47:12