using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net.Sockets; using System.Collections; using System.Threading; using System.Net; using System.Data.SqlClient; using System.Configuration; using System.Windows.Forms; namespace AGV_WPF.Services { public class Server { public Server() { //clientTable = new Hashtable(); try { using (SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["ConnString"])) { con.Open(); databaseStr = con.Database; con.Close(); } } catch (System.Exception ex) { databaseStr = "Error"; } } string databaseStr; private string localIP; public string LocalIP { get { return localIP; } set { if(localIP != value) localIP = value; } } private int port; public int Port { get { return port; } set { if(port != value) port = value; } } public TcpListener server = null; public Thread thread = null; public Thread receiveThread = null; public Thread sendThread = null; public static Hashtable clientTable = new Hashtable(); public bool IsThreadActive = false;//监听线程是否活动状态 public delegate void InvokeDelegate(); public static event EventHandler ClientChanged; void ConnectHandler() { try { IPAddress[] address = Dns.GetHostAddresses(Dns.GetHostName()); for (int i = 0; i < address.Count();i++ ) { if (address[i].AddressFamily.ToString().ToLower()=="internetwork" && address[i].ToString() == LocalIP) { server = new TcpListener(IPAddress.Parse(LocalIP), Port); server.Start(); break; } else if (i == address.Count() - 1) { MessageBox.Show("IP地址不存在"); //throw new Exception("IP地址不存在"); return; } } } catch (System.Exception ex) { //MessageBox.Show(ex.Message); throw new Exception(ex.Message); } while (IsThreadActive) { if (server.Pending()) { TcpClient client = server.AcceptTcpClient(); receiveThread = new Thread(ReceiveHandler); receiveThread.IsBackground = true; clientTable.Add(client, receiveThread); if (ClientChanged != null) { ClientChanged(clientTable, null); } receiveThread.Start(client); } else { Thread.Sleep(3000);//3秒扫描一次 } } } void ReceiveHandler(object o) { TcpClient client = o as TcpClient; int i = 0; byte[] buffer = new byte[1024]; while (true) { if (client.Client.Poll(-1, SelectMode.SelectRead)) { try { i = client.Client.Receive(buffer); } catch (System.Net.Sockets.SocketException ex) { if (clientTable.ContainsKey(client)) { client.Close(); clientTable.Remove(client); if (ClientChanged != null) { ClientChanged(clientTable, null); } //MessageBox.Show("客户端强制下线"); } break; } if (i == 0) { if (clientTable.ContainsKey(client)) { client.Close(); clientTable.Remove(client); if (ClientChanged != null) { ClientChanged(clientTable, null); } } break; } /* else if (i > 0) { string str = System.Text.Encoding.Default.GetString(buffer, 0, i); client.Client.Send(new byte[1]); }*/ } } } void SendHandler() { byte[] buffer = System.Text.Encoding.Default.GetBytes(string.Format("#{0}#", databaseStr)); while (true) { if (IsThreadActive) { foreach (DictionaryEntry dic in clientTable) { if (dic.Key != null) { TcpClient client = dic.Key as TcpClient; if (client != null) { try { client.Client.Send(buffer); } catch (System.Exception ex) { continue; } } } } } Thread.Sleep(3000); } } public void Open(string ip,int port) { if (thread != null && thread.ThreadState == ThreadState.Running) { //MessageBox.Show("正在监听中......"); return; } try { this.LocalIP = ip; this.Port = port; thread = new Thread(new ThreadStart(ConnectHandler)); thread.IsBackground = true; sendThread = new Thread(SendHandler); sendThread.IsBackground = true; IsThreadActive = true; thread.Start(); sendThread.Start(); } catch (System.Exception ex) { //MessageBox.Show(ex.Message); throw new Exception(ex.Message); //return; } } public void Close() { if (thread != null) { IsThreadActive = false; thread.Abort(); } if (sendThread != null) { sendThread.Abort(); } foreach (DictionaryEntry dic in clientTable) { if (dic.Value != null) { Thread t = dic.Value as Thread; if (t != null) { t.Abort(); } } } if (server != null) server.Stop(); clientTable.Clear();//移除所有客户信息 } public static byte[] HexToByte(string msg) { msg = msg.Replace(" ", "");//移除空格 if (msg.Length % 2 != 0) msg = msg.Substring(0, msg.Length - 1); byte[] comBuffer = new byte[msg.Length / 2]; for (int i = 0; i < msg.Length; i += 2) { comBuffer[i / 2] = (byte)Convert.ToByte(msg.Substring(i, 2), 16); } return comBuffer; } } }