public static void SendData(string msg) { LogInfo.Log.WriteInfo(LogInfo.LogType.Info, msg); byte[] buf = System.Text.Encoding.GetEncoding(936).GetBytes(msg); byte[] buf1 = new byte[buf.Length + 1]; Array.Copy(buf, 0, buf1, 0, buf.Length); buf1[buf1.Length - 1] = 0; dict.setUsed(true); try { foreach (string key in dict.Keys) { TcpInSocket t = (TcpInSocket)dict[key]; if (t.mySocket != null) { t.SendData(buf1); } else { dict.Remove(key); } } } finally { dict.setUsed(false); } }
/// <summary> ///监听客户端接收数据 /// </summary> private static void StartListen() { try { while (bRunning) { if (myListener.Poll(1000, SelectMode.SelectRead)) { Socket mySocket = myListener.Accept(); if (mySocket.Connected) { string key = mySocket.RemoteEndPoint.ToString(); TcpInSocket tTcpInSocket = new TcpInSocket(1, key); tTcpInSocket.OnReceive += rcdataHandler; tTcpInSocket.OnClose += new d_RemoveDict(RemoveDict); tTcpInSocket.mySocket = mySocket; System.Threading.Thread thread1 = new Thread(new ThreadStart(tTcpInSocket.SocketReceiveData)); thread1.Start(); //加进字典 dict.setUsed(true); try { if (dict.Contains(key)) { TcpInSocket t = (TcpInSocket)dict[key]; if (t.mySocket != null) { t.mySocket.Close(); } dict.Remove(key); } dict.Add(key, tTcpInSocket); } finally { dict.setUsed(false); } } } else { System.Threading.Thread.Sleep(50); } } myListener.Close(); myListener = null; } catch (Exception ee) { if (bRunning) { LogInfo.Log.WriteInfo(LogInfo.LogType.Error, "监听客户端错误:" + ee.ToString() + "\r\n"); bRunning = false; MessageBox.Show("网络连接出错,请重新启动监控程序。如果还有错误,请检查网络连接。", "错误"); System.Windows.Forms.Application.Exit(); } } }
/// <summary> /// 关闭线程 /// </summary> public static void Stop() { try { bRunning = false; thread.Join(); thread_other.Join(); thread_news.Join(); dict.setUsed(true); try { foreach (string key in dict.Keys) { TcpInSocket t = (TcpInSocket)dict[key]; if (t.mySocket != null) { t.mySocket.Close(); } } dict.Clear(); } finally { dict.setUsed(false); } dict_other.setUsed(true); try { foreach (string key in dict_other.Keys) { TcpInSocket t = (TcpInSocket)dict_other[key]; if (t.mySocket != null) { t.mySocket.Close(); } } dict_other.Clear(); } finally { dict_other.setUsed(false); } dict_news.setUsed(true); try { foreach (string key in dict_news.Keys) { TcpInSocket t = (TcpInSocket)dict_news[key]; if (t.mySocket != null) { t.mySocket.Close(); } } dict_news.Clear(); } finally { dict_news.setUsed(false); } } catch (Exception ee) { LogInfo.Log.WriteInfo(LogInfo.LogType.Error, "结束监听客户端错误:" + ee.ToString() + "。\r\n"); } }