Phpsocket communication demonstration and socket operation
Prepare a Java course design, an address book. Adopts the C/S architecture. The client uses java FX and Java, the server uses php, and socket for communication.
Next we will talk about socket communication in php:
Let's talk about TCP/IP and UDP first. With the increasing popularity of Internet applications, I believe many people have heard of these protocols more or less. What exactly are these protocols?
1. what are TCP/IP and UDP?
TCP/IP (Transmission Control Protocol/Internet Protocol) is an industrial standard Protocol set designed for WANs. TCP/IP protocol families include transport layer, network layer, and link layer.
User Data Protocol (UDP) is the Protocol corresponding to TCP. It belongs to the TCP/IP protocol family.
The following describes their relationships:
There is no socket here, so where is the socket? What's the purpose? Don't worry. next we will introduce the relationship between socket and them. Same.
Now you can understand the relationship between them. So what is socket? What's the purpose?
2. what is socket? What is the purpose?
Socket is an intermediate software abstraction layer for communications between the application layer and the TCP/IP protocol family. it is a group of interfaces. In the design mode, Socket is actually a facade mode, which hides the complex TCP/IP protocol family behind the Socket interface. for users, a set of simple interfaces are all, let the Socket organize the data to conform to the specified protocol.
Since socket is a set of encapsulated interfaces, how can we use it for communication? What is the specific process? Let's take a closer look at our call process. First, our phone number must be in the listening status, right. If not, it will certainly not receive calls from others. When a person calls the phone, he must first dial the phone number. The number is the target and unique one. After dialing, the phone will start to connect. after the phone is connected, you can start to talk. after the chat is over, you need to stop the phone so that others can connect to the phone. The same is true for Sockets. the server must first establish a socket to listen to a port on its computer. when a client creates a socket to initiate a connection request, it will accept the request. in this way, information can be transmitted, disable socket after transmission. Of course, the server can also initiate a connection request to the client and start communication. This is different from ajax and supports two-way communication. See the figure below:
Start with the server. The server first initializes the Socket, then binds it to the port (bind), listens to the port (listen), calls accept, and waits for the client to connect. At this time, if a client initializes a Socket and connects to the server (connect), if the connection is successful, the connection between the client and the server is established. The client sends a data request. the server receives the request and processes the request. then, the response data is sent to the client. the client reads the data and closes the connection. the interaction ends.
3. socket related functions:
Socket_accept () accepts a Socket connection
Socket_bind () binds the socket to an IP address and port.
Socket_clear_error () clears socket errors or the final error code
Socket_close () closes a socket resource
Socket_connect () starts a socket connection
Socket_create_listen () opens a socket listener on the specified port.
Socket_create_pair () generates a pair of non-differentiated sockets into an array.
Socket_create () generates a socket, which is equivalent to the data structure of a socket.
Socket_get_option () obtain the socket option
Socket_getpeername () obtains the IP address of a remote host similar to that of a remote host.
Socket_getsockname () gets the IP address of the local socket
Socket_iovec_add () add a new vector to a scattered/aggregated array
Socket_iovec_alloc () this function creates an iovec data structure that can send and receive read/write data.
Socket_iovec_delete () deletes an allocated iovec
Socket_iovec_fetch () returns the data of the specified iovec resource.
Socket_iovec_free () releases an iovec resource.
Socket_iovec_set () sets the new value of iovec data
Socket_last_error () obtains the final error code of the current socket.
Socket_listen () listens to all connections from the specified socket
Socket_read () reads data of the specified length
Socket_readv () reads data from scattered/aggregate arrays
Socket_recv () ends data from the socket to the cache
Socket_recvfrom () accepts data from the specified socket. If no value is specified, the current socket is used by default.
Socket_recvmsg () receives messages from iovec
Socket_select () multi-path selection
Socket_send () this function sends data to the connected socket
Socket_sendmsg () sends a message to the socket
Socket_sendto () sends a message to the socket of the specified address
Socket_set_block () is set to block mode in socket
Set the socket in socket_set_nonblock () to non-block mode.
Socket_set_option () sets socket options
Socket_shutdown () function allows you to close the read, write, or specified socket
Socket_strerror () returns a detailed error of the specified error number.
Socket_write () writes data to the socket cache
Socket_writev () writes data to a distributed/aggregate array
4. socket communication demonstration:
// Server:
= 5) {break ;};} socket_close ($ msgsock) ;}while (true); socket_close ($ sock);?>
// Client
";}While ($ out = socket_read ($ socket, 8192) {echo" received the server's return message! \ N "; echo" accept the following content: ", $ out;} echo" close SOCKET... \ n "; socket_close ($ socket); echo" close OK \ n ";?>
Note: 1) the server must run in CLI mode, that is, in command line mode. Do not use the cgi format (find the directory where php.exe is located, and then run the following code, the php Server file;
2) run netstat-ano in the dos window to check port usage.
5. encapsulate the socket into a class:
// ServerSocket. class. php
// Client socket operation
Server_host = $ host; $ this-> server_port = $ port; $ this-> CreateSocket ();} // Create a socket and bind it to the listening port private function createSocket () {if ($ this-> create_socket = socket_create (AF_INET, SOCK_STREAM, SOL_TCP) = false) {echo "socket_create () failed. reason :". socket_strerror (socket_last_error ()). "\ n";} if (socket_bind ($ this-> create_socket, $ this-> server_host, $ this-> server_port) = false) {echo "socket_bind () failed. reason :". socket_strerror (socket_last_error ($ this-> create_socket )). "\ n";} if (socket_listen ($ this-> create_socket, 5) = false) {echo "socket_listen () failed. reason :". socket_strerror (socket_last_error ($ this-> create_socket )). "\ n" ;}}// initiate a connection to the target host to public function connectClient () {if (socket_getpeername ($ this-> create_socket, $ this-> client_host, $ this-> client_port) = null) {echo "socket_getpeername () failed. reason :". socket_strerror (socket_last_error ($ this-> create_socket )). "\ n";} if (socket_connect ($ this-> create_socket, $ this-> client_host, $ this-> client_port) = false) {echo "socket_connect () failed. reason :". socket_strerror (socket_last_error ($ this-> create_socket )). "\ n" ;}}// accept the connection to obtain a socket resource, and want the client to read and transmit information public function wr () {do {// loop to prevent blocking delay if ($ this-> accept_socket = socket_accept ($ this-> create_socket) = null) {echo "socket_accept () failed. reason :". socket_strerror (socket_last_error ($ this-> create_socket )). "\ n"; break;} $ this-> get_data = socket_read ($ this-> accept_socket, 8192 ); $ this-> send_data = $ this-> operateData ($ this-> get_data); if (socket_write ($ this-> accept_socket, $ this-> send_data, strlen ($ this-> send_data) = false) {echo "socket_write () failed reason :". socket_strerror (socket_last_error ($ this-> accept_socket )). "\ n" ;}socket_close ($ this-> accept_socket) ;}while (true) ;}// data processing private function operateData () {return ;} // disable listening socket private function closeSocket () {socket_close ($ this-> createSocket);} // destructor public function _ destruct () {$ this-> closeSocket ();}}
// ClientSocket. class. php // client socke operation class Socket {private $ host; // connection socket host private $ port; // socket port number private $ error = array (); private $ socket = null; // The Connection ID of the socket: private $ queryStr = ""; // public function _ construct ($ host, $ port) {if (! Extension_loaded ("sockets") {exit ("open socket extension");} if (empty ($ host) exit ("Enter the target address "); if (empty ($ port) exit ("enter a valid port number"); $ this-> host = $ host; $ this-> port = $ port; $ this-> CreateSocket (); // create a connection} // Create a socket private function CreateSocket (){! $ This-> socket & $ this-> socket = socket_create (AF_INET, SOCK_STREAM, SOL_TCP); // create socket $ r = @ socket_connect ($ this-> socket, $ this-> host, $ this-> port); if ($ r) {return $ r ;} else {$ this-> error [] = socket_last_error ($ this-> socket); return false ;}// write data to the socket server and read public function wr ($ contents) {$ this-> queryStr = ""; $ this-> queryStr = $ contents ;! $ This-> socket & $ this-> CreateSocket (); $ contents = $ this-> fliterSendData ($ contents); $ result = socket_write ($ this-> socket, $ contents, strlen ($ contents); if (! Intval ($ result) {$ this-> error [] = socket_last_error ($ this-> socket); return false;} $ response = socket_read ($ this-> socket, 12048); if (false ===$ response) {$ this-> error [] = socket_last_error ($ this-> socket); return false;} return $ response ;} // filter sent data. private function fliterSendData ($ contents) {// process written data. return $ contents;} // all error information. public function getError () {return $ this-> error;} // last error message public function getLastError () {return $ this-> error (count ($ this-> error ));} // Obtain the last message public function getLastMsg () {return $ this-> queryStr;} public function getHost () {return $ this-> host ;} public function getPort () {return $ this-> port;} // close socket connection private function close () {$ this-> socket & socket_close ($ this-> socket); // close the connection $ this-> socket = null; // connection resource Initialization} public function _ destruct () {$ this-> close ();}}