Basic principles of phpsocket | server. php | client. php
Basic principles of php socket:
Server: Create a socket = bind the socket to the specified IP address and port = listen to all connection requests of the socket = respond or return data
Client: create a socket = connection request socket = send data to socket = read socket response data
(~ _~) If you do not understand the problem, please correct it ~~~
- Server. php
- $ Host = '1970. 168.0.10 ';
- $ Port = 88888;
- If ($ socket = socket_create (AF_INET, SOCK_STREAM, SOL_TCP )){
- Echo "socket create success. \ n ";
- }
- If ($ bind = socket_bind ($ socket, $ host, $ port )){
- Echo "socket bind success. \ n ";
- }
- If ($ listen = socket_listen ($ socket )){
- Echo "socket listening... \ n ";
- }
- If ($ connect = socket_accept ($ socket )){
- Echo "socket accept a connect success. \ n ";
- }
- // ================================================ ==================== //
- Socket_write ($ connect, 'I am from Server. php at DateTime:'. date ('Y-m-d H: I: s'). "\ n ");
- // ================================== Send to the client ==================== =========================================== //
- // ================================================ ================== //
- $ Read = socket_read ($ connect, 1024 );
- Echo $ read;
- // ===================Accept messages sent from the client =========================== ========== //
- // While ($ connect = socket_accept ($ socket )){
- // $ Read = socket_read ($ connect, 1024 );
- // Echo $ read;
- //}
- // Cyclically accept
- Client. php
- $ Host = '1970. 168.0.10 ';
- $ Port = 88888;
- If ($ socket = socket_create (AF_INET, SOCK_STREAM, SOL_TCP )){
- Echo "socket create success. \ n ";
- }
- Socket_connect ($ socket, $ host, $ port );
- // ================================================ ============================== //
- Socket_write ($ socket, 'I am from client. php at DateTime:'. date ('Y-m-d H: I: s'). "\ n ");
- // ============================== Send a request to the server ==================== ========================================= //
- // ================================================ ============================== //
- $ Read = socket_read ($ socket, 1024 );
- Echo $ read;
- // =========================Accept the returned data from the server ======== //
|