123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527 |
- 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();
- }
- }
- }
|