.net平台下C#socket通信(中)

时间:2022-06-28 01:22:14

1、正常通信中握手建立

2、一对多的通信

3、发送接收数据格式转换

4、资源释放

5、开启并保持服务监听

1、握手建立正常的通信通道

  项目需要通信的双方(假设是一个上位机、一个下位机)之间需要建立一个稳定的通道,以便进行通信。本项目中具体操作是:上位机作为服务器,下位机作为客户端,同时制定通信协议。上位机首先打开监听等待建立通道,下位机主动连接上位机后发送连接成功的信息到上位机,上位机根据通信协议发送数据到下位机,此时通道已经建立。但为了保险起见(同时遵循三次握手),客户端再次发送数据到上位机告知通道建立完毕。

2、一对多通信

  项目需求是一个上位机多个下位机,这就确定了上位机做为服务器端,下位机作为客户端主动连接服务器。一对一通信时只有一个socket通道,因此无论是上位机还是下位机在发送和接收数据的时候都不会存在数据乱发乱收的情况。一对多意味着上位机和下位机会建立起多个通道,因此在发送数据时需要记录哪一个下位机处于哪个socket通道中,以便进行逻辑处理。本文处理一对多通信的过程是:

1)首先建立一个对话类Session:

public class Session { public Socket ClientSocket { get; set; }//客户端的socket public string IP;//客户端的ip public Session(Socket clientSocket) { this.ClientSocket = clientSocket; this.IP = GetIPString(); } public string GetIPString() { string result = ((IPEndPoint)ClientSocket.RemoteEndPoint).Address.ToString(); return result; } }

2)在服务端socket监听时:

IPEndPoint loaclEndPoint = new IPEndPoint(IPAddress.Any, Port); SocketLister = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); SocketLister.Bind(loaclEndPoint); try { SocketLister.Listen(MaxConnection); while (IsRunning) { ClientSocket = SocketLister.Accept(); //保存socket Session newSession = new Session(ClientSocket); lock (sessionLock) { sessionTable.Add(newSession.IP, newSession); } SocketConnection socketConnection = new SocketConnection(ClientSocket); socketConnection.ReceiveDatagram();//接收数据 } } catch (SocketException ex) { }



//声明

public Hashtable sessionTable = new Hashtable ();//包括客户端会话

private object sessionLock = new object();

 

为了便于理解,把整个服务端socket的建立都写在上面。

3)发送数据到不同的客户端

Hashtable ht = serverSocket.sessionTable; foreach (Session session in ht.Values) { if (session.IP == "127.0.0.1")//example { SocketConnection socketConnection = new SocketConnection(session.ClientSocket); string str = "C300010002D2"; byte[] sendBytes = StrToHexByte(str); socketConnection.Send(sendBytes); } }

SocketConnection类已经被使用多次,写在下面:

public class SocketConnection:IDisposable { public ServerSocket Server { get; set; } public Byte[] MsgBuffer = null; private int totalLength = 0; public int CurrentBufferLength; private Socket _ClientSocket = null; public Socket ClientSock { get{ return this._ClientSocket; } } public SocketConnectionType Type { get; private set; } #region Constructor public SocketConnection(ServerSocket server, Socket sock) { this.Server = server; this._ClientSocket = sock; this.Type = SocketConnectionType.Server; } public SocketConnection(Socket sock) { this._ClientSocket = sock; this.Type = SocketConnectionType.Client; } #endregion #region Events public SocketConnectionDelegate OnConnect = null;//是否连接 public SocketConnectionDelegate OnLostConnect = null;//中断连接 public ReceiveDataDelegate OnReceiveData = null;//接收数据 #endregion #region Connect public void Connect(IPAddress ip, int port) { this.ClientSock.BeginConnect(ip, port, ConnectCallback, this.ClientSock); } private void ConnectCallback(IAsyncResult ar) { try { Socket handler = (Socket)ar.AsyncState; handler.EndConnect(ar); if (OnConnect != null) { OnConnect(this); } ReceiveDatagram(); } catch (SocketException ex) { } } #endregion #region Send public void Send(string data) { Send(System.Text.Encoding.UTF8.GetBytes(data)); } public void Send(byte[] byteData) { try { int length = byteData.Length; byte[] head = BitConverter.GetBytes(length); byte[] data = new byte[head.Length + byteData.Length]; Array.Copy(head, data, head.Length); Array.Copy(byteData, 0, data, head.Length, byteData.Length); this.ClientSock.BeginSend(data, 0, data.Length, 0, new AsyncCallback(SendCallback), this.ClientSock); } catch (SocketException ex) { } } private void SendCallback(IAsyncResult ar) { try { Socket handler = (Socket)ar.AsyncState; handler.EndSend(ar); } catch (SocketException ex) { } } #endregion #region ReceiveDatagram public void ReceiveDatagram() { SocketStateObject state = new SocketStateObject(); state.workSocket = _ClientSocket; _ClientSocket.BeginReceive(state.buffer, 0, SocketStateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state); } private void ReceiveCallback(IAsyncResult ar) { SocketStateObject state = (SocketStateObject)ar.AsyncState; Socket handler = state.workSocket; if (handler.Connected) { try { state.bytesRead = handler.EndReceive(ar); if (state.bytesRead > 0) { OnDataRecivedCallback(state.buffer, state.bytesRead); Array.Clear(state.buffer, 0, state.buffer.Length); state.bytesRead = 0; handler.BeginReceive(state.buffer, 0, SocketStateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state); } else { //if (OnDisconnect != null) //{ // OnDisconnect(this); //} Dispose(); } } catch (SocketException ex) { } } } private void ReceiveCallBack00(IAsyncResult ar) { try { int REnd = _ClientSocket.EndReceive(ar); if (REnd > 0) { OnDataRecivedCallback(MsgBuffer, REnd ); Array.Clear(MsgBuffer, 0, MsgBuffer.Length); REnd = 0; _ClientSocket.BeginReceive(MsgBuffer, 0, MsgBuffer.Length, 0, new AsyncCallback(ReceiveCallBack00), null); } else { if (OnLostConnect != null) { OnLostConnect(this); } Dispose(); } } catch (Exception ex) { } } private void OnDataRecivedCallback(byte[] data, int length) { if (length > 0) { if (this.MsgBuffer == null) { byte[] bytelength = new byte[4]; Array.Copy(data, bytelength, 4); this.totalLength = BitConverter.ToInt32(bytelength, 0); this.MsgBuffer = new byte[this.totalLength]; this.CurrentBufferLength = 0; } if (this.totalLength > 0) { int offset = 0; if (CurrentBufferLength == 0) { offset = 4; } if (length + this.CurrentBufferLength >= this.totalLength + offset) { int len = this.totalLength - CurrentBufferLength; Array.Copy(data, offset, this.MsgBuffer, this.CurrentBufferLength, len); byte[] tmp = this.MsgBuffer.Clone() as byte[]; OnReceiveData(new MessageData(this, tmp)); this.MsgBuffer = null; if (length - len - offset > 0) { tmp = new byte[length - len - offset]; Array.Copy(data, offset + len, tmp, 0, tmp.Length); OnDataRecivedCallback(tmp, tmp.Length); } } else { Array.Copy(data, offset, this.MsgBuffer, this.CurrentBufferLength, length - offset); this.CurrentBufferLength += length - offset; } } else { } } } public void Dispose() { try { this.ClientSock.Shutdown(SocketShutdown.Both); this.ClientSock.Close(); this.Server = null; //if (OnLostConnect != null) //{ // OnLostConnect(this); //} } catch { } } #endregion }

3、处理需要发送和接收到的数据