C # socket communication (medium) on the. net platform ),
In the previous article, C # socket communication (I) on the. net platform introduced the basic principles and the most basic communication methods of socket communication. On this basis, this article makes a simple summary of the issues frequently encountered during socket communication, all of which are some minor issues in the project, so it is easy to use next time, at the same time, I would like to give a rough suggestion to colleagues who encounter some problems when using socket. Thank you for your suggestions.
This article focuses on:
1. Handshake established in normal communication
2. One-to-multiple communication
3. Convert the sending and receiving data format
4. release resources
5. Enable and maintain Service Listening
1. handshake to establish a normal communication channel
A stable channel needs to be established between the two parties (assuming a host computer and a lower computer) for communication. In this project, the upper computer acts as the server, the lower computer acts as the client, and the communication protocol is developed. The upper computer first opens the listener and waits for a channel to be established. The lower computer actively connects to the upper computer and sends the successful connection information to the upper computer. The upper computer sends data to the lower computer according to the communication protocol. At this time, the channel has been established. But for the sake of insurance (three handshakes are followed at the same time), the client sends the data again to the host computer to inform the channel that the establishment is complete.
2. One-to-multiple communication
The project requires a host machine with multiple lower computers, which determines that the upper computer serves as the server, and the lower computer actively connects to the server as the client. One-to-one communication only has one socket channel. Therefore, no data is sent or received by the upper computer or lower computer. One-to-many means that the upper computer and the lower computer will establish multiple channels. Therefore, when sending data, you need to record which lower computer is in which socket channel for logical processing. The process of one-to-multiple communication is as follows:
1) first create a dialog Session:
Public class Session {public Socket ClientSocket {get; set;} // client socket public string IP; // Client ip public Session (Socket clientSocket) {this. clientSocket = clientSocket; this. IP = GetIPString ();} public string GetIPString () {string result = (IPEndPoint) ClientSocket. remoteEndPoint ). address. toString (); return result ;}}
2) When the server socket listens:
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 (); // save socket Session newSession = new Session (ClientSocket); lock (sessionLock) {sessionTable. add (newSession. IP, newSession);} SocketConnection socketConnection = new SocketConnection (ClientSocket); socketConnection. receiveDatagram (); // receives data} catch (SocketException ex ){}
// Statement
Public Hashtable sessionTable = new Hashtable (); // includes client sessions
Private object sessionLock = new object ();
For ease of understanding, write the establishment of the entire server socket above.
3) send data to different clients
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); } }
3. process the data to be sent and received
The project needs to be logically processed by the upper computer, and then sent to the lower computer through the TCP/IP protocol. The lower computer sends confirmation information to the upper computer while receiving the data. During the project process, the upper computer needs to debug whether the data sending and receiving are successful during the development process. Here, the USR-tcp.pdf tool is used. However, there is a problem that the lower computer sends and receives byte arrays. How should the developed upper computer send and receive data? In. on the net platform, C # socket communication (on) has a server-side sending and receiving function. When sending data, the string to be sent is converted to a byte array, during receiving, the byte array is converted to a hexadecimal string. As follows:
// Convert the byte array to a hexadecimal string public string ByteToHexStr (byte [] bytes) {string str = ""; if (bytes! = Null) {for (int I = 0; I <bytes. length; I ++) {str + = bytes [I]. toString ("X2") ;}} return str ;}// convert the string to a hexadecimal byte array public byte [] StrToHexByte (string data) {data = data. replace ("", ""); if (data. length % 2 )! = 0) {data + = "";} byte [] bytes = new byte [data. length/2]; for (int I = 0; I <bytes. length; I ++) {bytes [I] = Convert. toByte (data. substring (I * 2, 2), 16);} return bytes ;}
4. release resources
The Development Project platform is. net, the tool vs2010, and the language is C #. Because. net has a garbage collection mechanism, the managed resources generated in actual development are automatically released by the system. Winform was used for development in this project. In this process, a problem was found: the system running the Form was not completely closed. Find out the reason. The reason is that some resources are not released. The resources generated by socket sockets happen to be unmanaged resources, which indicates that socket resources in the system are not completely released. Therefore, a resource release function is written:
public void Dispose() { try { this.ClientSocket.Shutdown(SocketShutdown.Both); this.ClientSocket.Dispose(); this.ClientSocket.Close(); this.ClientSocket = null; } catch { } }
The functions of the above functions are to release the resources generated by the socket. This problem still exists after the call. After debugging, it is found that although the listener client resources that generate the socket channel are released, the serversocket on the server is not released, so the following function is available:
Public void CloseSocket () {if (serverSocket! = Null) {serverSocket. SocketLister. Dispose (); serverSocket. SocketLister = null; serverSocket. Dispose (); // call the previous function serverSocket = null ;}}
After the preceding functions are completed, the resources generated by socket are indeed released, and the system can actually close the function after the form function is disabled. This resource seems to have been released, but then a new problem arises:
When can I call a function to release resources?
My personal opinion:
1) called upon system Suspension
2) called when the socket channel is interrupted
Supplement:
5. Enable and maintain Service Listening
In socket communication, the socket listener of the server must be enabled and maintained all the time. Only in this way can the server listen to the connected client at any time. Project Example:
Private void button#click (object sender, RoutedEventArgs e) {Thread thread = new Thread (new ThreadStart (StartServer); thread. start ();} public void StartServer () {int port = Convert. toInt32 (GetText (this. tbPort); string ipStr = GetText (this. tbServerIPStr); if (serverSocket = null) {serverSocket = new ServerSocket (port); serverSocket. start (ipStr); //} else {MessageBox. show ("listener enabled") ;}} public void Start (string ipStr) {IPEndPoint localEndPoint = new IPEndPoint (IPAddress. any, Port); // IPEndPoint localEndPoint = new IPEndPoint (IPAddress. parse (ipStr), Port); SocketLister = new Socket (AddressFamily. interNetwork, SocketType. stream, ProtocolType. tcp); SocketLister. bind (localEndPoint); try {SocketLister. listen (MaxConnection); while (IsRunning) {ClientSocket = SocketLister. accept (); // save socket Session newSession = new Session (ClientSocket); lock (sessionLock) {sessionTable. add (newSession. IP, newSession);} SocketConnection socketConnection = new SocketConnection (ClientSocket); socketConnection. receiveDatagram () ;}} catch (SocketException ex ){}}
Explanation: click the button to open a new thread. The execution method is StartServer. StartServer calls the Start method. In the Start method, an endless loop is used to enable the thread and keep the listener.
Source code or tutorial for B/S and C/S mixed-mode system development on the. net platform
Create a new WEB project, and then create a new WINFORM project under this solution. This solution contains BS, And the CS project is what you call hybrid development. That is to say, if you create a WEB project, and then create a WINFORM project, it is a hybrid development. The advantage is that projects can be referenced by each other.
In net, what technologies can we use to develop c/s Systems?
You can use win form for the c/s system .. Net and win form are both Microsoft platforms, but they are in two different directions ,. net is mainly used for web development, not for c/s systems. win form can be used for desktop programs and c/s systems.