The C#socket communication under the. NET platform (above) introduces the basic principle of socket communication and the most fundamental means of communication. This article on this basis on the socket communication often encountered problems to do a simple summary, are some small problems in the project, take here to facilitate the next use, at the same time, when using the socket has a few problems in the colleagues have a superficial suggestion. Please put forward the deficiencies, thank you.
This article mainly describes:
1. Handshake establishment in normal communication
2, one-to-many communication
3. Send and receive data format conversion
4. Release of resources
1, shake hands to establish a normal communication channel
The project needs to establish a stable channel between the two parties (assuming a host computer, a subordinate machine) to communicate. The specific operation of this project is: the host computer as a server, the lower machine as a client, at the same time to develop a communication protocol. The host computer first opens the listening wait to establish the channel, the next computer actively connects the host computer after sending the information to the host computer, the host computer according to the communication protocol to send data to the next machine, at this time the channel has been established. But for the sake of insurance (at the same time three handshake), the client sends the data again to the host computer to inform the channel is established.
2, one-to-many communication
Project demand is a host computer multiple lower machine, which determines the host computer as the server side, the next computer as a client active connection server. There is only one socket channel in a single communication, so neither the host computer nor the lower computer will have data hair when sending and receiving data. A one-to-many means that the host computer and the next opportunity to establish a plurality of channels, so when sending data need to record which lower computer in which socket channel, for logical processing. The process of handling one-to-many communication in this article is:
1) First set up a dialog class session:
Public classSession { PublicSocket Clientsocket {Get;Set; }//socket for Client Public stringIP;//IP of the client PublicSession (Socket clientsocket) { This. Clientsocket =Clientsocket; This. IP =getipstring (); } Public stringgetipstring () {stringresult =((IPEndPoint) clientsocket.remoteendpoint). Address.tostring (); returnresult; } }
2) When the server socket is listening:
IPEndPoint Loaclendpoint =NewIPEndPoint (Ipaddress.any, Port); Socketlister=Newsockets (AddressFamily.InterNetwork, SocketType.Stream, protocoltype.tcp); Socketlister.bind (Loaclendpoint); Try{Socketlister.listen (maxconnection); while(isrunning) {Clientsocket=socketlister.accept (); //Save SocketSession newsession =NewSession (Clientsocket); Lock(Sessionlock) {Sessiontable.add (Newsession.ip, newsession); } socketconnection socketconnection=Newsocketconnection (Clientsocket); Socketconnection.receivedatagram ();//Receive Data } } Catch(SocketException ex) {}
Statement
Public Hashtable sessiontable = new Hashtable ();//Includes client sessions
Private Object Sessionlock = new Object ();
To facilitate understanding, the entire service-side socket is set up on top.
3) Send data to different clients
Hashtable HT =serversocket.sessiontable; foreach(Session sessioninchht. Values) {if(session.) IP = ="127.0.0.1")//Example{socketconnection socketconnection=NewSocketConnection (session. Clientsocket); stringstr ="C300010002D2"; byte[] Sendbytes =strtohexbyte (str); Socketconnection.send (sendbytes); } }
3. Processing data that needs to be sent and received
The project needs to be the host computer to obtain data for logical processing, and then through the TCP/IP protocol sent to the lower machine, the next computer in the receiving of data while sending confirmation information to the host computer. Project process, the host computer in the development process need to debug its sending data, receive data is successful, here with the help of usr-tcp232 gadgets. However, when it comes to a problem, the sending and receiving of the lower computer are all byte arrays, then how should the host computer send and receive the data? In the. NET Platform C#socket Communication (above), there is a server-side send and receive functions, send data when the string to be sent to a byte array, receive and then convert the byte array to 16 binary string. As follows:
//byte array converted to 16 binary string Public stringBYTETOHEXSTR (byte[] bytes) { stringstr =""; if(Bytes! =NULL) { for(inti =0; I < bytes. Length; i++) {str+ = Bytes[i]. ToString ("X2"); } } returnstr; } //converts a string to a 16 binary byte array Public byte[] Strtohexbyte (stringdata) {Data= data. Replace (" ",""); if(Data. Length%2) !=0) {Data+=" "; } byte[] bytes =New byte[Data. Length/2]; for(inti =0; I < bytes. Length; i++) {Bytes[i]= Convert. ToByte (data. Substring (i *2,2), -); } returnbytes; }
4. Release of resources
The development project use platform is. NET, tool vs2010, language is C #, because. NET has a garbage collection mechanism, so the managed resources that are generated in real-world development are automatically released by the system. Developed using WinForm when doing this project, a problem was found in this process: the system that is running on the Close form form is not completely closed. The reason for the lookup should be that there are resources not being released. The source of the socket socket is the unmanaged resource, which indicates that the socket resource in the system has not been completely released. So write a resource release function:
public void Dispose () { try { this this this this . Clientsocket = null catch {} }
The function of the above functions is to release the resources generated by the socket, after the call to find that there is still this problem, after several debugging found that although the socket channel to generate the listener client resources to complete the release, the server side of the ServerSocket is not released, so there is the next function:
Public void closesocket () { ifnull) { serverSocket.SocketLister.Dispose (); NULL ; Serversocket.dispose ();//The last function called null; } }
After the above function is completed, the resources generated by the socket socket are actually released and the system can be closed after the form is closed. This resource seems to have been released, but then the new problem arises:
When and where do you call the function that frees the resource?
Personal Simple view:
1) Call when system aborts
2) Called when the socket channel is interrupted
C#socket communication under the. NET Platform (Medium)