


Commonly used functions in php socket programming and the implementation of simple c/s interaction
The content of this article is about commonly used functions in php socket programming and the implementation of simple c/s interaction. The content is very detailed. Friends in need can refer to it. I hope it can help you.
Socket Introduction
Official explanation of Socket:
The most commonly used solution in network programming is the Client/Server (client/server) model. In this scenario the client application requests services from the server program. A service program usually listens for requests for the service at a well-known address. That is to say, the service process remains dormant until a client makes a connection request to the service's address. At this moment, the service program is "awakened" and provides services to the client - reacting appropriately to the client's request. In order to facilitate network programming of this Client/Server model, in the early 1990s, Microsoft and several other companies jointly developed a set of network programming interfaces under WINDOWS, namely the Windows Sockets specification. It is not a network protocol, but a network programming interface. A set of open network programming interfaces under Windows that support multiple protocols. Now Winsock has basically become protocol-independent. You can use Winsock to call functions of multiple protocols, but the TCP/IP protocol is more commonly used. Socket actually provides a communication port in the computer through which it can communicate with any computer that has a Socket interface. The application transmits on the network, and the information received is realized through this Socket interface
We can simply understand Socket as a pipe that can connect different computer applications on the network, and transfer a bunch of data from If the A end of the pipe is thrown in, it will come out from the B end of the pipe (it can also come out from the C, D, E, F... ends).
Note
: We will use different words to modify socket in different contexts. You only need to have a concept of it, because socket itself has no real meaning. Entity
Socket function introduction
Socket communication will proceed through several stages: Socket creation, Socket binding, Socket monitoring, Socket sending and receiving, and Socket closing. We list them below. Several common functions that are most commonly used and essential in PHP network programming are further explained.
socket_create
TODO: Create a new socket resource
Function prototype: resource socket_create (int $domain, int $type, int $protocol)
It contains three parameters, as follows:
domain: AF_INET, AF_INET6, AF_UNIX, the definition of
AF
isaddress family
, address Family means, we commonly use ipv4, ipv6type: SOCK_STREAM, SOCK_DGRAM, etc. The most commonly used one is
SOCK_STREAM
, a SOCKET type based on byte stream, It is also the type used by TCP protocol-
protocol: SOL_TCP, SOL_UDP This is the specific transmission protocol used. Generally, we choose TCP for reliable transmission, and we generally choose UDP protocol for game data transmission
socket_bind
TODO: Bind the created socket resource to a specific ip address and port
Function prototype: bool socket_bind (resource $socket, string $ address [, int $port = 0 ] )
It contains three parameters, as follows:
socket: Use
socket_create
The created socket resource can be considered as the id corresponding to the socketaddress: ip address
port: listening port number, WEB server default Port 80
socket_listen
TODO: Monitor the sending and receiving operations of socket resources at a specific address
Function prototype: bool socket_listen (resource $socket [ , int $backlog = 0 ] )
It contains two parameters, as follows:
socket: Created using
socket_create
Socket resourcebacklog: The maximum length of the connection queue waiting to be processed
socket_accept
TODO: After listening, receive a The upcoming new connection, if the connection is successfully established, will return a new socket handle (you can understand it as a child process, usually the parent process is used to receive new connections, and the child process is responsible for specific communication)
Function prototype: resource socket_accept ( resource $socket )
socket: socket resource created using
socket_create
socket_write
TODO: Send the specified data to the corresponding socket pipe
Function prototype: int socket_write (resource $socket, string $buffer [, int $length])
socket: socket resource created using
socket_create
buffer: written to
socket
resource Data inlength: Controls the length of
buffer
written to thesocket
resource, if the length is greater thanbuffer
’s capacity, take the capacity ofbuffer
socket_read
TODO: Get the transmitted data
Function prototype: int socket_read (resource $socket, int $length)
socket: The socket resource created using
socket_create
length:
buffer# in the
socketresource ##The length
Function prototype:
void socket_close (resource $socket)
- socket: The resources generated by
socket_accept
or
socket_createcannot be used to close
streamresources
resource stream_socket_server ( string $local_socket [, int &$errno [, string &$errstr [, int $flags = STREAM_SERVER_BIND | STREAM_SERVER_LISTEN [, resource $context ]]]] )
- local_socket: protocol name://address:port number
- errno: error code
- errstr: Error message
- #flags: Only use part of the function
- context: Resource stream created using the
stream_context_create
function Context
socket implements C/S interaction
Based on the above functions, we can easily build a socket communication program (here I hope Readers can create a separate directory such assocket (because we will create many files later). We first edit a server program
server.php, as follows:
<?php date_default_timezone_set("Asia/Shanghai"); error_reporting(E_NOTICE ); /* 确保在连接客户端时不会超时 */ set_time_limit(0); $ip = '127.0.0.1'; $port = 8090; /* +------------------------------- * @socket通信整个过程 +------------------------------- * @socket_create * @socket_bind * @socket_listen * @socket_accept * @socket_read * @socket_write * @socket_close +-------------------------------- */ /*---------------- 以下操作都是手册上的 -------------------*/ if(($sock = socket_create(AF_INET,SOCK_STREAM,SOL_TCP)) < 0) { echo "socket_create() Why failure is:".socket_strerror($sock)."\n"; } if(($ret = socket_bind($sock,$ip,$port)) < 0) { echo "socket_bind() Why failure is:".socket_strerror($ret)."\n"; } if(($ret = socket_listen($sock,4)) < 0) { echo "socket_listen() Why failure is:".socket_strerror($ret)."\n"; } echo "Start time:".date('Y-m-d H:i:s') . PHP_EOL; echo "Listening at ".$ip.':'.$port.PHP_EOL; do { /* 创建新的连接 */ if (($msgsock = socket_accept($sock)) < 0) { echo "socket_accept() failed: reason: " . socket_strerror($msgsock) . "\n"; break; } else { # 连接成功输出 Socket id $i = (int)$msgsock; echo "welcome client $i"; # 向客户端通信(反馈) $msg ="连接成功!\n"; socket_write($msgsock, $msg, strlen($msg)); } socket_close($msgsock); } while (true); socket_close($sock); ?>Then Edit a client program
client.php as follows:
<?php set_time_limit(0); $port = 8090; $ip = "127.0.0.1"; /* +------------------------------- * 客户端 socket 连接整个过程 +------------------------------- * @socket_create * @socket_connect * @socket_write * @socket_read * @socket_close +-------------------------------- */ /** * @socket_connect:客户端发起套接字连接 * @param socket resource $socket 创建的$socket资源 * @param address string SOCK_STREAM IP地址|Unix套接字 * @param port int 端口 */ /** * @socket_create:创建并返回一个套接字 * @param domain string AF_INET IPV4 网络协议 * @param type string SOCK_STREAM 全双工字节流(可用的套接字类型) * @param protocol string SOL_TCP 具体协议(IPV4下的TCP协议) * @param return 套接字 */ $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($socket < 0) { echo "socket_create() failed: reason: " . socket_strerror($socket) . "\n"; }else { echo "try to connect '$ip' port: '$port'...\n"; } $result = socket_connect($socket, $ip, $port); #socket_connect的返回值应该是boolean值 if ($result < 0) { echo "socket_connect() failed.\nReason: ($result) " . socket_strerror($result) . "\n"; }else { # 连接成功输出提示信息 echo "connect successfully\n"; # 向服务端发送数据 socket_write($socket, " hello ", 1024); # 获取服务端数据 $result = socket_read($socket, 1024); echo "服务器回传数据为:" . $result; echo "CLOSE SOCKET...\n"; socket_close($socket); echo "CLOSE OK\n"; } ?>Then we open the terminal (command line) and enter the file directory to execute in sequence:
php server.php php client.phpThe running effect is as follows:
NoteWhen the server is listening, the process is suspended and no other operations can be performed. You may need to start another terminal to execute the client Terminal program
How does PHP and MySql realize background data reading? (Code)
thinkphp5 uses the workerman timer to crawl regularly Get the code of the site contentThe above is the detailed content of Commonly used functions in php socket programming and the implementation of simple c/s interaction. For more information, please follow other related articles on the PHP Chinese website!

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 Mac version
God-level code editing software (SublimeText3)

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software
