using System; using System.Runtime.Serialization.Formatters.Binary; using System.IO; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; namespace CommonLib { public class Communicate { private Socket mySocket; private IPEndPoint myIPEndPoint; private byte[] tempByte = new byte[8]; private string receiveMess; private NetPara _netPara; public bool FormOpening = false; public NetPara CommunicatePara { get { return this._netPara; } } public string ReadMess { get { if (receiveMess != null) { return this.receiveMess; } else return "0000000"; } } public string NetName { set; get; } private bool conResult = false; public delegate void ConnectResultEventHandler(object sender, ResultEventArgs e); public delegate void MessageReceivedEventHandler(object sender, MessageEventArgs e); public event MessageReceivedEventHandler MessageReceived;//接受到数据事件 public event ConnectResultEventHandler ConnectedResult;//连接成功事件 public Communicate(string commName,string ip,int port ) { try { this.NetName = commName; this._netPara = new NetPara(commName); this.myIPEndPoint = new IPEndPoint(IPAddress.Parse(ip), port); mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); } catch (Exception ex) { System.Windows.Forms.MessageBox.Show("ERROR IP,Please reset." + ex.Message + ";" + ex.StackTrace); } System.Threading.Thread connectThread = new System.Threading.Thread(Connect); connectThread.IsBackground = true; connectThread.Start(); System.Threading.Thread receiveThread = new System.Threading.Thread(ReceiveMessage); receiveThread.IsBackground = true; receiveThread.Start(); } public class ResultEventArgs : EventArgs { public readonly bool conResult; public ResultEventArgs(bool conResult) { this.conResult = conResult; } } public class MessageEventArgs : EventArgs { public readonly string Message; public readonly byte[] byteMes; public MessageEventArgs(string Message, byte[] byteMes) { this.Message = Message; this.byteMes = byteMes; } //public MessageEventArgs(byte[] byteMes) //{ // this.byteMes = byteMes; //} } public string IpAddress//定义属性--IP地址 { set { this.myIPEndPoint.Address = IPAddress.Parse(value); } get { return this.myIPEndPoint.Address.ToString(); } } public int Port//定义属性--端口号 { set { this.myIPEndPoint.Port = value; } get { return myIPEndPoint.Port; } } int numberOfException = 0; public void Connect()//尝试连接服务器或者客户端 { while (true) { if (CommunicatePara.客户端Or服务器 == NetBehavior.Client) { try { System.Threading.Thread.Sleep(300); mySocket.Connect(myIPEndPoint); conResult = true; ResultEventArgs e = new ResultEventArgs(conResult); ResultToDo(e); receiveMess = ""; break; } catch { conResult = false; ResultEventArgs e = new ResultEventArgs(conResult); ResultToDo(e); } } else { System.Threading.Thread.Sleep(500); try { this.mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); myIPEndPoint.Address = IPAddress.Parse(this.IpAddress); mySocket.Bind(myIPEndPoint); mySocket.Listen(1); mySocket = mySocket.Accept(); conResult = true; ResultEventArgs e = new ResultEventArgs(conResult); ResultToDo(e); } catch (Exception ex) { if ((ex is System.Net.Sockets.SocketException) && (numberOfException < 4)) { if (mySocket.IsBound) { EndPoint edp = mySocket.RemoteEndPoint; mySocket.Shutdown(SocketShutdown.Both); mySocket.Close(100); Connect(); numberOfException++; } } else { System.Windows.Forms.MessageBox.Show("网络可能没有成功连接,发送数据时出现错误!\n" + ex.ToString()); } } return; } } } public void closeSocket() { if (!FormOpening) { if (this.mySocket.Connected) { this.mySocket.Shutdown(SocketShutdown.Both); } if (this.mySocket != null) { this.mySocket.Close(100); this.mySocket = null; } } } protected virtual void ResultToDo(ResultEventArgs e) { if (ConnectedResult != null) { ConnectedResult(this, e); } } int headSize = 8;//包头长度 固定8 byte StopByte = 0x00; int totalLen; int bodySize; int MID; byte[] surplusBuffer = null;//完整的数据包 byte[] recvByte = null;//待发送的字节 public void ReceiveMessage()//接收数据 { while (FormOpening) { System.Threading.Thread.Sleep(20); if (mySocket != null) { if (mySocket.Connected) { int numReceive = 0; try { if (surplusBuffer == null) { numReceive = mySocket.Receive(tempByte, SocketFlags.None); } else { numReceive = mySocket.Receive(surplusBuffer, SocketFlags.None); } if (numReceive == 0) { byte[] temp = Encoding.Default.GetBytes(" "); mySocket.Send(temp); } } catch { if (this.mySocket != null) { conResult = false; ResultEventArgs e = new ResultEventArgs(conResult); ResultToDo(e); if (this.mySocket.Connected) { this.mySocket.Shutdown(SocketShutdown.Both); } this.mySocket.Close(); this.mySocket = null; GC.Collect(); this.mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); System.Threading.Thread connectThread = new System.Threading.Thread(Connect); connectThread.IsBackground = true; connectThread.Priority = System.Threading.ThreadPriority.Normal; connectThread.Start(); } } if (numReceive > 0) { if (numReceive == 1) continue; if (surplusBuffer == null)//判断是不是第一次接收,为空则是第一次 { if (tempByte[0].Equals(0x00)) { bodySize = int.Parse(Encoding.ASCII.GetString(tempByte, 1, 4));//从包头里面分析出包体长度 surplusBuffer = new byte[bodySize - headSize + 1]; recvByte = new byte[headSize - 1]; Buffer.BlockCopy(tempByte, 1, recvByte, 0, headSize - 1); } else { bodySize = int.Parse(Encoding.ASCII.GetString(tempByte, 0, 4));//从包头里面分析出包体长度 surplusBuffer = new byte[bodySize - headSize]; recvByte = tempByte; } //try //{ // bodySize = int.Parse(Encoding.ASCII.GetString(tempByte, 0, 4));//从包头里面分析出包体长度 // surplusBuffer = new byte[bodySize - headSize]; // recvByte = tempByte; //} // catch //{ // bodySize = int.Parse(Encoding.ASCII.GetString(tempByte, 1, 4));//从包头里面分析出包体长度 // surplusBuffer = new byte[bodySize - headSize+1]; // recvByte = new byte[bodySize]; // Buffer.BlockCopy(tempByte, 1, recvByte, 0, headSize - 1); //} // } } else { // String receiveMess = bodySize.ToString("0000") + MID.ToString("0000") + Encoding.ASCII.GetString(surplusBuffer, 0, bodySize - headSize); recvByte = recvByte.Concat(surplusBuffer).ToArray(); MessageEventArgs e = new MessageEventArgs(receiveMess, recvByte); if (MessageReceived != null) { MessageReceived(this, e); } surplusBuffer = null;//设置空 回到原始状态 recvByte = null; totalLen = 0;//清0 bodySize = 0; MID = 0; } } } } } } public void SendMessage(string s)//发送数据 { if (FormOpening) { if (mySocket != null) { if (mySocket.Connected) { byte[] buffer = Encoding.Default.GetBytes(s); try { mySocket.Send(buffer, buffer.Length, SocketFlags.None); } catch { System.Windows.Forms.MessageBox.Show("网络可能没有成功连接,发送数据时出现错误!"); } } else { if (mySocket.Connected) { byte[] buffer = Encoding.Default.GetBytes(s); try { mySocket.Send(buffer, buffer.Length, SocketFlags.None); } catch { System.Windows.Forms.MessageBox.Show("网络可能没有成功连接,发送数据时出现错误!"); } } else { if (mySocket.Connected) { byte[] buffer = Encoding.Default.GetBytes(s); try { mySocket.Send(buffer, buffer.Length, SocketFlags.None); } catch { System.Windows.Forms.MessageBox.Show("网络可能没有成功连接,发送数据时出现错误!"); } } else { System.Windows.Forms.MessageBox.Show("网络未连接!"); } } } } } } ////public System.Windows.Forms.DialogResult SetPara() ////{ //// return new frmTcpIpConfig(this).ShowDialog(); ////} } [Serializable] public enum NetBehavior { Server = 1, Client = 2 } [Serializable] public class NetPara { private string _ip = "192.168.0.16"; private int _port = 8080; private NetBehavior _behavior = NetBehavior.Client; private string _netParaName = System.Windows.Forms.Application.StartupPath + "\\dn.np"; public string Ip { get { return _ip; } set { _ip = value; } } public int Port { get { return _port; } set { _port = value; } } public NetBehavior 客户端Or服务器 { set { this._behavior = value; } get { return this._behavior; } } public string NetParaName { private set { this._netParaName = value; } get { return this._netParaName; } } public void SetPara(string ip, int port, NetBehavior 客户端Or服务器) { try { this._ip = ip; this._port = port; this._behavior = 客户端Or服务器; } catch (Exception ex) { System.Windows.Forms.MessageBox.Show("ERROR\r\n" + ex.Message, "Set param..."); } } public void SavePara() { try { BinaryFormatter bf = new BinaryFormatter(); FileStream fs = new FileStream(_netParaName, FileMode.OpenOrCreate, FileAccess.Write); bf.Serialize(fs, this); fs.Flush(); fs.Close(); //System.Windows.Forms.MessageBox.Show("用户数据保存成功!", "用户保存..."); } catch (Exception ex) { System.Windows.Forms.MessageBox.Show("Save fail!\r\n " + ex.Message, "Save param......"); } } public void IniPara() { //if (System.IO.File.Exists(_netParaName)) { try { //BinaryFormatter bf = new BinaryFormatter(); //FileStream fs = new FileStream(_netParaName, FileMode.Open, FileAccess.Read); //NetPara netPara = (NetPara)bf.Deserialize(fs); //fs.Flush(); //fs.Close(); //this.Ip = netPara.Ip; //this.Port = netPara.Port; this.客户端Or服务器 = NetBehavior.Client; //this.NetParaName = netPara.NetParaName; } catch (Exception ex) { System.Windows.Forms.MessageBox.Show("Init Fail!\r\n" + ex.Message, "Init..."); } } } public NetPara(string paraName) { this._netParaName = string.Format("{0}\\{1}.np", System.Windows.Forms.Application.StartupPath, paraName); IniPara(); } } }