The server side of the TCP connection involves the following three functions:
/***************************** ** Function function: server monitoring ** Input parameters: ** Output parameters: ******************************/ private void ServerListen(){}
/****************************** ** Function function: Used to connect with the client ** Input parameters: ** Output parameters: ******************************/ private void AcceptConnect(){}
/****************************** ** Function function: Accept the information sent back by the client ** Input parameters: ar: information sent back by the client ** Output parameters: ******************************/ private void ReadCallback(IasyncResult ar){}
The relationship diagram of the three is as follows:
The specific code is as follows:
1、ServerListen()
private bool isExit = false; TcpListener listener; //Used for thread synchronization, the initial state is set to non-terminated state, and the manual reset method is used private EventWaitHandle allDone = new EventWaitHandle (false, EventResetMode.ManualReset); /****************************** ** author: *** ** Change time: 2012-12-26 ******************************/ #region server listening method private void ServerListen() { //Since the server needs to serve multiple clients, a thread needs to be created to listen for client connection requests ThreadStart ts = new ThreadStart(AcceptConnect); Thread myThread = new Thread(ts); myThread.Start(); } #endregion
2、AcceptConnect()
/****************************** ** author: *** ** Change time: 2012-12-26 ******************************/ #region Get connected with the client private void AcceptConnect() { //Get all IP addresses of the machine IPAddress[] localips = Dns.GetHostAddresses(Dns.GetHostName()); foreach (IPAddress ip in localips) { //Find all local IP addresses that conform to the IPV4 protocol if (ip.AddressFamily == AddressFamily.InterNetwork) { IPAddress ip4; ip4 = ip; listener = new TcpListener(ip4, 5000); listener.Start(); break; } } //Refer to the callback method to be called when the asynchronous operation completes AsyncCallback callback = new AsyncCallback(AcceptTcpClientCallback); while (isExit == false) { //Set the state of the event to non-terminating allDone.Reset(); // Start an asynchronous operation to accept incoming connection attempts listener.BeginAcceptTcpClient(callback, listener); //Block the current thread until the client connection signal is received allDone.WaitOne(); Thread.Sleep(100); } } #endregion
3、AcceptTcpClientCallback()
/****************************** ** author: *** ** Change time: 2012-12-26 ******************************/ #region Callback function for connecting to the client //ar is an interface of type IAsyncResult, indicating that the status of the asynchronous operation is passed by listener.BeginAcceptTcpClient(callback, listener) private void AcceptTcpClientCallback(IAsyncResult ar) { //Set the event state to the terminated state, allowing one or more waiting threads to continue allDone.Set(); TcpListener myListener = (TcpListener)ar.AsyncState; //Receive incoming connections asynchronously and create new TcpClient objects to handle remote host communication TcpClient client = myListener.EndAcceptTcpClient(ar); ReadWriteObject readWriteObject = new ReadWriteObject(client); readWriteObject.netStream.BeginRead(readWriteObject.readBytes, 0, readWriteObject.readBytes.Length, ReadCallback, readWriteObject); } #endregion
4、ReadCallback()
byte[] tem = new byte[24]; byte[] Msgbody; byte [] ErrorEndTime; ByteToObject bytetoobject = new ByteToObject(); /****************************** ** author: *** ** Change time: 2012-12-02 ******************************/ #region Receive the information sent by the client, ar is the information sent by the client in the asynchronous method private void ReadCallback(IAsyncResult ar) { ReadWriteObject readWriteObject = (ReadWriteObject)ar.AsyncState; int length = readWriteObject.netStream.EndRead(ar); tem = new byte[24]; Array.Copy(readWriteObject.readBytes, 0, tem, 0, 24); //MsgHead is a custom structure MsgHead msghead = (MsgHead)bytetoobject.BytesToStuct(tem, typeof(MsgHead)); if (length > 0 && msghead.Sync == 0x4D) { switch (msghead.MsgType) { //According to the header of the received message, perform the following operations } } }
The server side of the TCP connection involves the following three functions:
/***************************** ** Function function: server monitoring ** Input parameters: ** Output parameters: ******************************/ private void ServerListen(){}
/****************************** ** Function function: Used to connect with the client ** Input parameters: ** Output parameters: ******************************/ private void AcceptConnect(){}
/****************************** ** Function function: Accept the information sent back by the client ** Input parameters: ar: information sent back by the client ** Output parameters: ******************************/ private void ReadCallback(IasyncResult ar){}
The relationship diagram of the three is as follows:
The specific code is as follows:
1、ServerListen()
private bool isExit = false; TcpListener listener; //Used for thread synchronization, the initial state is set to non-terminated state, and the manual reset method is used private EventWaitHandle allDone = new EventWaitHandle (false, EventResetMode.ManualReset); /****************************** ** author: *** ** Change time: 2012-12-26 ******************************/ #region server listening method private void ServerListen() { //Since the server needs to serve multiple clients, a thread needs to be created to listen for client connection requests ThreadStart ts = new ThreadStart(AcceptConnect); Thread myThread = new Thread(ts); myThread.Start(); } #endregion
2、AcceptConnect()
/****************************** ** author: *** ** Change time: 2012-12-26 ******************************/ #region Get connected with the client private void AcceptConnect() { //Get all IP addresses of the machine IPAddress[] localips = Dns.GetHostAddresses(Dns.GetHostName()); foreach (IPAddress ip in localips) { //Find all local IP addresses that conform to the IPV4 protocol if (ip.AddressFamily == AddressFamily.InterNetwork) { IPAddress ip4; ip4 = ip; listener = new TcpListener(ip4, 5000); listener.Start(); break; } } //Refer to the callback method to be called when the asynchronous operation completes AsyncCallback callback = new AsyncCallback(AcceptTcpClientCallback); while (isExit == false) { //Set the state of the event to non-terminating allDone.Reset(); // Start an asynchronous operation to accept incoming connection attempts listener.BeginAcceptTcpClient(callback, listener); //Block the current thread until the client connection signal is received allDone.WaitOne(); Thread.Sleep(100); } } #endregion
3、AcceptTcpClientCallback()
/****************************** ** author: *** ** Change time: 2012-12-26 ******************************/ #region Callback function for connecting to the client //ar is an interface of type IAsyncResult, indicating that the status of the asynchronous operation is passed by listener.BeginAcceptTcpClient(callback, listener) private void AcceptTcpClientCallback(IAsyncResult ar) { //Set the event state to the terminated state, allowing one or more waiting threads to continue allDone.Set(); TcpListener myListener = (TcpListener)ar.AsyncState; //Receive incoming connections asynchronously and create new TcpClient objects to handle remote host communication TcpClient client = myListener.EndAcceptTcpClient(ar); ReadWriteObject readWriteObject = new ReadWriteObject(client); readWriteObject.netStream.BeginRead(readWriteObject.readBytes, 0, readWriteObject.readBytes.Length, ReadCallback, readWriteObject); } #endregion
4、ReadCallback()
byte[] tem = new byte[24]; byte[] Msgbody; byte [] ErrorEndTime; ByteToObject bytetoobject = new ByteToObject(); /****************************** ** author: *** ** Change time: 2012-12-02 ******************************/ #region Receive the information sent by the client, ar is the information sent by the client in the asynchronous method private void ReadCallback(IAsyncResult ar) { ReadWriteObject readWriteObject = (ReadWriteObject)ar.AsyncState; int length = readWriteObject.netStream.EndRead(ar); tem = new byte[24]; Array.Copy(readWriteObject.readBytes, 0, tem, 0, 24); //MsgHead is a custom structure MsgHead msghead = (MsgHead)bytetoobject.BytesToStuct(tem, typeof(MsgHead)); if (length > 0 && msghead.Sync == 0x4D) { switch (msghead.MsgType) { //According to the header of the received message, perform the following operations } } }