You're not a stranger to TCP/IP, UDP,socket programming. With the development of network technology, these words are filled with our ears. Then I would like to ask:
1. What is TCP/IP,UDP?
2. where is the socket?
3. What is a socket?
4. Will you use them?
What is TCP/IP ,UDP ?
TCP/IP (transmission Control protocol/internet Protocol) is a protocol/inter-network protocol, an industry-standard set of protocols designed for wide area networks (WANs).
UDP (user Data Protocol, Subscriber Datagram Protocol) is the protocol that corresponds to TCP. It is a part of the TCP/IP protocol family.
Here is a diagram showing the relationship of these protocols.
The TCP/IP protocol family includes transport layer, network layer, and link layer. Now you know the relationship between TCP/IP and UDP.
Where's the socket?
In Figure 1, we don't see the socket shadow, so where is it? Or use a diagram to speak, at a glance.
The original socket is here.
What is a socket?
A socket is an intermediate software abstraction layer that the application layer communicates with the TCP/IP protocol family, which is a set of interfaces. In design mode, the socket is actually a façade mode, it is the complex TCP/IP protocol family hidden behind the socket interface, for the user, a set of simple interface is all, let the socket to organize data to meet the specified protocol.
Will you use them?
Predecessors have done a lot of things to us, the communication between the network is a lot simpler, but after all, there is still a lot of work to do. Previously heard socket programming, think it is more advanced programming knowledge, but as long as understand how the socket programming principle, the mysterious veil also opened.
A scene in the life. You have to call a friend, dial first, a friend hears a phone call, and then you and your friend establish a connection, you can talk. When the communication is over, hang up the phone and end the conversation. The scene in life explains this work principle, perhaps the TCP/IP protocol family is born in the life, this is not necessarily.
Start with the server side. The server-side initializes the socket, then binds to the port (BIND), listens to the port (listen), calls the Accept block, waits for the client to connect. At this point if a client initializes a socket and then connects to the server (connect), the client-server connection is established if the connection is successful. The client sends the data request, the server receives the request and processes the request, then sends the response data to the client, the client reads the data, closes the connection, and ends the interaction at the end.
Socket correlation function:
----------------------------------------------------------------------------------------------
Socket_accept () accepts a socket connection
Socket_bind () binds the socket to an IP address and port
Socket_clear_error () Clears the socket error or the last error code
Socket_close () Close a socket resource
Socket_connect () Start a socket connection
Socket_create_listen () Open a socket listener on the specified port
Socket_create_pair () produces a pair of indistinguishable sockets into an array
Socket_create () produces a socket equivalent to a data structure that produces a socket
Socket_get_option () Get socket options
Socket_getpeername () Gets the IP address of a remote similar host
Socket_getsockname () Gets the IP address of the local socket
Socket_iovec_add () Add a new vector to a scatter/aggregate array
Socket_iovec_alloc () This function creates a IOVEC data structure that can send the received read and write
Socket_iovec_delete () Delete an already assigned Iovec
Socket_iovec_fetch () returns the data for the specified Iovec resource
Socket_iovec_free () releasing a Iovec resource
Socket_iovec_set () Sets the new data value of the Iovec
Socket_last_error () Gets the last error code for the current socket
Socket_listen () listens for all connections by the specified socket
Socket_read () reads the specified length of data
SOCKET_READV () reads data from a scatter/aggregate array
SOCKET_RECV () end data from socket to cache
Socket_recvfrom () accepts data from the specified socket, if not specified, the default current socket
Socket_recvmsg () receive messages from Iovec
Socket_select () multi-channel selection
Socket_send () This function sends the data to the connected socket
SOCKET_SENDMSG () Send message to socket
Socket_sendto () sends a message to the socket at the specified address
Socket_set_block () set as block mode in socket
Socket_set_nonblock () set to non-block mode in socket
Socket_set_option () Set socket options
Socket_shutdown () This function allows you to close a read, write, or specified socket
Socket_strerror () returns a detailed error for the specified error number
Socket_write () write data to the socket cache
Socket_writev () write data to a scatter/aggregate array
Case ONE: Socket communication Demo
Server-side:
1 <?php 2//Ensure that the client is connected without time-out 3 set_time_limit (0); 4 5 $ip = ' 127.0.0.1 '; 6 $port = 1935; 7 8/* 9 +-------------------------------* @socket communication The whole process one by one +-------------------------------* @socket_crea TE13 * @socket_bind14 * @socket_listen15 * @socket_accept16 * @socket_read17 * @socket_write18 * @ SOCKET_CLOSE19 +--------------------------------*/21///----------------The following operations are on the manual-------------------*/23 i F (($sock = Socket_create (af_inet,sock_stream,sol_tcp)) < 0) {echo "Socket_create () failed due to:". Socket_strerror ($soc k). " \ n ";}26 ($ret = Socket_bind ($sock, $ip, $port)) < 0) {echo" Socket_bind () failed due to: ". Socket_strerror ($ret). "\ n";}30 if (($ret = Socket_listen ($sock, 4)) < 0) {echo "Socket_listen () failed because:". Socket_strerror ($ret). " \ n ";}34 $count = 0;36 Notoginseng do {($msgsock = socket_accept ($sock)) < 0) {" echo "socket_accept () Failed:reason: ". Socket_strerror ($msgsock). "\ n";BREAK;41} else {42 43//Sent to client $msg = "Test succeeded! \ n "; Socket_write ($msgsock, $msg, strlen ($msg)); echo" Test succeeded AH \ n "; $buf = Socket_r EAD ($msgsock, 8192); $talkback = "message Received: $BUF \ n"; Echo $talkback; 53 54 if (+ + $count >= 5) {break;56};57}60//echo $buf; socket_clo SE ($msgsock); Socket_close (true);?> ($sock);
This is the server-side code for the socket. Then run CMD, note that it is your own program to store the path AH.
No reflection, the current service side of the program has started to run, the port has started to listen. Run Netstat-ano to see the port condition, mine is port 1935.
Look, the port is already in the listening state. Next we just run the client program to connect. On the Code
Press CTRL + C to copy the code<textarea></textarea>Press CTRL + C to copy the code
the client is already connected to the service side. Case two: Code explanation//set some basic variables$host ="192.168.1.99"; $port=1234;//setting the time-out periodSet_time_limit (0);//Create a socket$socket = Socket_create (Af_inet, Sock_stream,0) or Die ("Could not createsocket\n");//bind socket to port$result = Socket_bind ($socket, $host, $port) or Die ("Could not bind tosocket\n");//Start listening links$result = Socket_listen ($socket,3) or Die ("Could not set up socketlistener\n");//Accept Incoming Connections//another socket to handle communication$spawn = socket_accept ($socket) or Die ("Could not accept incomingconnection\n");//get input from the client$input = Socket_read ($spawn,1024x768) or Die ("Could not read input\n");//empty the input string$input =trim ($input);//processing client input and returning results$output = Strrev ($input)."\ n"; Socket_write ($spawn, $output, strlen ($output)) or Die ("Could not writeoutput\n");//Close SocketsSocket_close ($spawn); Socket_close ($socket); The following is a detailed description of each of these steps:1The first step is to create two variables to hold the IP address and port of the server on which the socket is running. You can set up your own server and port (this port can be a number from 1 to 65535), provided that the port is not in use. [Copy to Clipboard] PHP CODE://set two variables$host ="192.168.1.99"; $port=1234;2the Set_time_out () function can be used on the server side to ensure that PHP does not time out while waiting for the client to connect. [Copy to Clipboard] PHP CODE://Timeout periodSet_time_limit (0);3On the previous basis, it is now time to use the Socket_creat () function to create a socket-this function returns a socket handle that will be used in all subsequent functions. [Copy to Clipboard] PHP CODE://Create socket$socket = Socket_create (Af_inet, Sock_stream,0) or Die ("Could not createsocket\n");the first parameter "Af_inet" is used to specify the domain name, and the second argument "Sock_strem" tells the function what type of socket to create (in this case TCP type) so if you want to create a UDP socket, you can use the following code: [Copy to Clipboard] PHP CODE://Create socket$socket = Socket_create (Af_inet, Sock_dgram,0) or Die ("Could not createsocket\n");4. Once a socket handle is created, the next step is to specify or bind it to the specified address and port. This can be done through the Socket_bind () function. [Copy to Clipboard] PHP CODE://bind socket to specify address and port$result = Socket_bind ($socket, $host, $port) or Die ("Could not bind tosocket\n");5When the socket is created and bound to a port, you can start listening for external connections. PHP allows you to start a listener by the Socket_listen () function, and you can specify a number (in this case, the second parameter:3) [Copy to clipboard]php CODE://start listening for connections$result = Socket_listen ($socket,3) or Die ("Could not set up socketlistener\n");6until now, your server has done nothing but wait for a connection request from the client. Once a client's connection is received, the socket_accept () function starts to work, it receives the connection request and calls another child socket to process the client – Information between the servers. [Copy to Clipboard] PHP CODE://Accept Request Link//calling child socket processing information$spawn = socket_accept ($socket) or Die ("Could not accept incomingconnection\n");This sub-socket can now be used by subsequent client-server communications.7When a connection is established, the server waits for the client to send some input information, which can be obtained by the Socket_read () function and assign it to the PHP $input variable. [Copy to Clipboard] PHP CODE://Read Client input$input = Socket_read ($spawn,1024x768) or Die ("Could not read input\n");?&the Gt;socker_read parameter specifies the number of bytes to read, which you can use to limit the size of the data that is fetched from the client. Note: The Socket_read function will read the shell data until it encounters the \n,\t or the. The PHP script considers this character to be the input terminator.8The server must now handle the data that is sent by the client (in this case the processing consists of only the input of the data and the return to the client). This can be done by the Socket_write () function (which makes it possible to send a data stream back to the client by a communication socket) [ Copy to clipboard]php CODE://process client input and return data$output = Strrev ($input)."\ n"; Socket_write ($spawn, $output, strlen ($output)) or Die ("Could not writeoutput\n");9Once the output is returned to the client, the parent/The child socket should terminate [Copy to clipboard]php CODE by using the Socket_close () function://Close SocketsSocket_close ($spawn); Socket_close ($socket);
In-depth explanation: PHP socket Communication