类CSocketClient主要包括以下内容:
private TcpClient _client; public Thread _connectionThread; private StreamWriter _write; public ClientRecMsgClass GClientRecMsgClass1 = new ClientRecMsgClass(); private string hostname = Dns.GetHostName(); private string recMessage = ""; public string RecMessage { get { return recMessage; } set { recMessage = value; } } private int port = 0; public int Port { get { return port; } set { port = value; } } private string ip = ""; public string Ip { get { return ip; } set { ip = value; } }
public CSocketClient(string ipAddress, int portNumber) { port = portNumber; ip = ipAddress; ConnectToServer(); } public CSocketClient() { }
public void ConnectToServer() { try { _connectionThread = new System.Threading.Thread(new ThreadStart(ReceiveDataFromServer)); _connectionThread.IsBackground = true; _connectionThread.Priority = ThreadPriority.AboveNormal; _connectionThread.Name = "Handle Server"; _connectionThread.Start(); } catch (Exception ex) { //MessageBox.Show(this, ex.Message, "QuickBuild Client Sample"); } }
private void ReceiveDataFromServer() { try { _client = new TcpClient(ip, port); } catch (SocketException ex) { return; } NetworkStream netStream = null; try { netStream = _client.GetStream(); } catch (Exception ex) { return; } if (netStream.CanRead) { try { byte[] receiveBuffer = new byte[4096]; int bytesReceived; // Received byte count while ((bytesReceived = netStream.Read(receiveBuffer, 0, receiveBuffer.Length)) > 0) { recMessage = Encoding.ASCII.GetString(receiveBuffer, 0, bytesReceived);
GClientRecMsgClass1.ClientRecMsg1(GClientRecMsgClass1); if (_write != null) _write.Write(Encoding.ASCII.GetString(receiveBuffer, 0, bytesReceived)); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } StopClient(); }
private void StopClient() { if (_client != null) { _client.Close(); _connectionThread.Join(); } } private void UpdateGUI(string s) { }
public void SendMsgToServer(string sendData) { try { byte[] buffer = Encoding.Default.GetBytes(sendData); try { _client.Client.Send(buffer); } catch (Exception ex) { throw ex; } } catch { } }
public void SendMsgToServerByte(byte[] buffer) { try { try { _client.Client.Send(buffer); } catch (Exception ex) { throw ex; } } catch { } }
客户端处理事件:
#region 客户端处理事件 //声明客户端接收数据代理 public delegate void ClientRecMsg(object o); //声明一个类 public class ClientRecMsgClass { //声明一个事件 public event ClientRecMsg ClientRecMsgEvent1; //定义一个方法调用事件 public void ClientRecMsg1(object o) { if (ClientRecMsgEvent1 != null) { //调用事件的方法 ClientRecMsgEvent1(o); } } } #endregion
标签:try,string,C#,void,private,Modbus,Tcp,public,ex From: https://www.cnblogs.com/echo-efun/p/18439146