Recently in the research socket, today saw a very good article on the socket communication, so the collection, slowly pondering.
Before we talk about socket programming, let's look at several concepts that are closely related to socket programming:
1. TCP/IP Hierarchy model
Of course, we're only talking about the important four floors here.
01, Application Layer (application): The application layer is a very broad concept, there are some basic same system-level TCP/IP applications and application protocols, there are many enterprise applications and Internet applications. The HTTP protocol runs at the application level.
02, Transport Layer (Tanspot): The transport layer includes UDP and tcp,udp almost does not check the message, while TCP provides a transmission guarantee.
03, Network Layer (NETWOK): Network layer protocol consists of a series of protocols, including ICMP, IGMP, RIP, OSPF, IP (V4,V6) and so on.
04, Link layer (link): Also known as the Physical Data network interface layer, responsible for message transmission.
Then let's take a look at the TCP Hierarchy Model diagram
As you can see, the application runs at the application layer, at the transport layer, with the TCP header in front of the data,
The network layer adds a frame to the IP header, which is added to the data link layer.
2. Port
Port number range: 0-65535, which can represent a total of 65,536 numbers.
By port number can be divided into 3 major categories
(1) Recognized ports (wellknownports): from 0 to 1023, they are tightly bound (binding) to some services. Usually the communication of these ports clearly indicates the protocol of a certain service. For example: Port 80 is actually always HTTP traffic.
(2) Registration port (registeredports): from 1024 to 49151. They are loosely tied to some services. This means that there are many services bound to these ports, which are also used for many other purposes. For example: Many systems handle dynamic ports starting around 1024.
(3) dynamic and/or private ports (dynamicand/orprivateports): from 49152 to 65535. In theory, these ports should not be assigned to the service. In fact, machines typically allocate dynamic ports from 1024 onwards.
3.TCP and UDP messages
Let's take a look at the TCP and UDP message graph.
We can see that both TCP and UDP have checksums, but in UDP packets, checksums are generally not used, which speeds up the data transfer, but the accuracy of the information can be affected. In other words, the TCP protocol has checksums, in order to guarantee the accuracy of the transmitted data.
3.Socket
The socket includes the IP address and the port number, the program communicates through the socket, and the socket is equivalent to a component of the operating system. A socket is a communication mechanism between processes, often referred to as a "socket," which describes the IP address and port number, and is a handle to a communication chain. To put it bluntly, it is two programs for communication.
Life Case Comparison:
The communication between sockets can be analogous to the case of phone calls in life. Any user before the call, the first to occupy a telephone, equivalent to apply for a socket, but also to know the other person's number, the equivalent of a fixed socket, and then dial the caller, the equivalent of making a connection request. If the other party is present and free, pick up the telephone handset and the two sides can make a call. The two sides of the call process, is the direction of the telephone signal and the other side from the telephone to receive the signal process, the equivalent of sending data to the socket and receiving data from the socket. After the call ends, one side hangs up the phone, which is the equivalent of closing the socket and revoking the connection.
Note: The socket can communicate not only between two computers, but also between two programs on the same computer.
4, Port Advanced (in-depth)
Once a computer in the network is identified by an IP address, there may be many applications on the computer that provide services, each of which corresponds to a port.
There are many such hosts on the internet, which typically run multiple service software while providing several services, each of which opens a socket and binds to a port with different ports corresponding to different services (applications)
For example: HTTP using port 80, FTP using 21 port SMTP using 25 port
5.Socket classification
There are two main types of sockets:
Streaming sockets
is a connection-oriented socket that is secure, but inefficient, for connection-oriented TCP service applications
2, data-report socket
is a non-connected socket that corresponds to a non-connected UDP service application that is unsafe but highly efficient
6. Socket general Application Mode (server side and client)
Server-side sockets (minimum of two required)
01. One is responsible for receiving client connection requests (but is not responsible for communicating with the client)
02. Every successful connection to the client generates a socket for the corresponding complex communication on the server side.
021. Created when a client connection is received
022. Create a corresponding socket on the server side for each successful client request (responsible for communicating with the client)
Socket for Client
You must specify the server address and port to connect to
Initializes a server-side TCP connection by creating a socket object
Through, we can see, the first server will create a listener responsible for the socket, and then the client through the socket connection to the server designated port, the end of the server is responsible for monitoring the socket, monitoring the client has a connection, create a responsible and client communication socket.
Let's look at the more specific communication process for the socket:
The communication process of the socket
Server-side:
01, apply for a socket
02, bound to an IP address and on a port
03, turn on Listen, wait for receive connection
Client:
01, apply for a socket
02, Connection server (indicates IP address and port number)
After the server receives the connection request, a new socket (port greater than 1024) is created to connect with the client and communicates, and the original listener socket continues to listen.
Note: The socket responsible for communication cannot be created indefinitely, and the number created is related to the operating system.
Constructors for 7.Socket
Public Socket (addressfamily addressfamily,sockettype sockettype,protocoltype protocoltype)
AddressFamily: Specifies the addressing scheme that the socket uses to resolve addresses. For example: internetwork Indicates when the socket is connected using an IP version 4 address
SocketType: Defines the type of socket to open
The socket class uses the ProtocolType enumeration to notify the Windows Sockets API of the requested protocol
Attention:
1, the port number must be between 1 and 65535, preferably after 1024.
2, the remote host to be connected must be listening on the specified port, that is, you are not free to connect to the remote host.
Such as:
IPAddress addr = Ipaddress.parse ("127.0.0.1");
IPEndPoint ENDP = new IPEndPoint (addr,,9000);
Server binding First: Serverwelcomesocket.bind (ENDP)
Client reconnection: Clientsocket.connect (ENDP)
3, one socket can only connect one host at a time
4,socket cannot be used again after closing
5, each socket object can be connected to only one remote host. If you want to connect to more than one remote host, you must create multiple socket objects.
8.Socket Common Classes and methods
Related classes:
IPAddress: contains an IP address
IPEndPoint: Contains a pair of IP addresses and port numbers
Method:
Socket (): Create a socket
Bind (): Binds a local IP and port number (IPEndPoint)
Listen (): Let the socket listen for incoming connections eat that disease and specify the listening queue capacity
Connect (): Initialize the connection to another socket
Accept (): Receive the connection and return a new socket
Send (): Output data to socket
Receive (): reading data from the socket
Close (): Close socket, destroy connection
Next, we have a simple server and client communication case, to see the specific use of Sokcet, as follows:
Key code:
Server-side code:
1 private void Form1_Load (object sender, EventArgs e)
2 3 {4 5 control.checkforillegalcrossthreadcalls = false; 6 7} 8 9 private void Btnlisten_click (object sender, EventArgs e) 12 13 {14 15 IP address: IPAddress IP = ipaddress.parse (txtip.text); +//IPAddress IP = ipaddress.any; 20 21//Port number IPEndPoint point=new IPEndPoint (ip,int. Parse (Txtport.text)); 24 25//Create a listening socket * * AddressFamily.InterNetwork: Use the IP4 address. SocketType.Stream: Supports reliable, bidirectional, connection-based byte streams without duplicating data. This type of Socket communicates with a single peer host and requires a remote host connection before the communication begins. Stream uses Transmission Control Protocol (TCP) ProtocolType and internetworkaddressfamily. PROTOCOLTYPE.TCP: Using Transmission Control Protocol. 34 35 */36 37//Use IPV4 address, streaming socket, TCP protocol pass data the socket=new socket socket (Addr ESSFAMILY.INTERNETWORK,SOCKETTYPE.STREAM,PROTOCOLTYPE.TCP); 40 41//After you create a socket, you must tell the IP address and port number of the socket binding. 42 43 Let the socket listen to the point, try,//socket, which Port 50 51 Socket. Bind (point); 52 53//At the same time point over 10 clients, queued for the five-in-one socket. Listen (10); ShowMsg ("Server Start Monitoring"); The acceptinfo thread thread = new Thread (); Thread. IsBackground = true; The thread. Start (socket); (Exception ex) 68 69 {70 71 72 73 ShowMsg (ex. Message); 74 75} 76 77} 78 79//Socket for record communication dictionary<string,socket> Dic=new Dictionary<string, socket> (); A/private Socket client; 90-Acceptinfo (Object o) (the "O" Socket Socket): 91 while (true) 92 93 {94 95//Communication with socketRY 98 99 {100 101//create communication with SOCKET102 103 socket Tsocket = socket. Accept (); 104. String point = TSocket.RemoteEndPoint.ToString (); 106 107//ipendpoi NT EndPoint = (ipendpoint) client. remoteendpoint;108 109//string me = Dns.gethostname ();//Get the name of the machine 111//messagebo X.show (Me), 113 showmsg (point + "Connection succeeded! "); CboIpPort.Items.Add (point); 117 dic. ADD (Point, Tsocket); 118 119//Receive message 121 thread th = new Thread (receivemsg); 122 1 Th. IsBackground = true;124th. Start (Tsocket); 126 127}128 129 catch (Exception ex) 130 131 {132 133 ShowMsg (ex. Message); 134 135 break;136 137}138 139}140 141}142 143 Receive message 144 145 void Receivemsg (object o) 146 147 {148 149 Socket client = o as socket;15 0 151 while (true) 152 153 {154 155//Receive client sent over data 156 157 try158 15 9 {160 161///define a byte array to hold the data received from the client 162 163 byte[] buffer = new byte [1024 * 1024];164 165//Put the received data into buffer and return the length of the actual accepted data 166 167 int n = client. Receive (buffer); 168 169//Convert bytes to string 171 string words = Encoding.UTF8.GetString ( Buffer, 0, N); 172 173 174 175 showmsg (client. Remoteendpoint.tostring () + ":" + words); 176 177}178 179 catch (Exception ex) 180 181 {182 183 showmsg (ex. Message); 184 185 break;186 187}188 189}190 191}192 193 194 195 void ShoWmsg (String msg) 196 197 {198 199 txtlog.appendtext (msg+ "\ r \ n"); 200 201}202 203 204 205 private void Form1_formclosing (object sender, FormClosingEventArgs e) 206 207 {208 209//Closing a child thread when the main form is closed 210 211 212 213}214 215//Send message to client 216 217 private void Btnsend_click (object sender, Eve Ntargs e) 218 219 {221 try222 223 {224 225 showmsg (txtmsg.text); 226 227 String ip = cboipport.text;228 229 byte[] buffer = Encoding.UTF8.GetBytes (txtmsg.text); 23 0 231 Dic[ip]. Send (buffer); 232 233//client. Send (buffer), 234 235}236 237 catch (Exception ex) 238 239 {241 Show MSG (ex. Message); 242 243}244 245 246 247}
Client code:
1 Socket client = new socket (addressfamily.internetwork, SocketType.Stream, protocoltype.tcp);
2 3 private void Btnconnection_click (object sender, EventArgs e) 4 5 {6 7//target I connected to P 8 9 IPAddress IP = ipaddress.parse (txtip.text); Ten//ipaddress IP = ipaddress.any; 12 13//which app (port number) is connected to the destination IP? ) IPEndPoint point=new IPEndPoint (ip,int. Parse (Txtport.text)); Try 18 19 {20 21//Connect to server. Connect (point); ShowMsg ("connected successfully"); ShowMsg ("Server" + client.) Remoteendpoint.tostring ()); ShowMsg ("Client:" + client.) Localendpoint.tostring ()); 30 31//After the connection is successful, you can receive the information sent by the server. Th=new thread (receivemsg); The same as the th. IsBackground = true; The Panax notoginseng th. Start (); Max. (Exception ex) (ex) (SHOWMSG) Message); 46 47}48 49} 50 51//Receive server messages for the Receivemsg (). () (Tru e) (+) (byte[) buffer = new byte[1024 * 1024]; the net int n = client. Receive (buffer); A string s = Encoding.UTF8.GetString (buffer, 0, N); ShowMsg (client. Remoteendpoint.tostring () + ":" + s); The "Exception Ex" (The) Howmsg (ex. Message); The Bay of Bayi break; The "All-in-A-showmsg" (Stri ng msg) 94 Txtinfo.appendtext (msg+ "\ r \ n"), 98}100 101 102 103 Priva te void Btnsend_click (object sender, EventArgs e) 104 105 {106 107//client sends message to server 108 109 if (Client!=null) 111 {113 try114 115 {116 117 ShowMsg (Txtmsg.text); 118 119 byte[] buffer = Encoding.UTF8.GetBytes (txtmsg.text); 120 121 Client. Send (buffer); 122 123}124 catch (Exception ex) 126 127 {128 129 ShowMsg (ex. Message),}132 133}134 135 136 137}138 139 131 141 Privat e void Clientform_load (object sender, EventArgs e) 142 143 {144 145 CONTROL.CHECKFORILLEGALCROSSTHREADC Alls = false;146 147}
Article source http://www.cr173.com/html/19555_1.html
C # Socket Communication