search

What is php socket?

Jul 05, 2017 am 09:37 AM
phpsocketwhat is

This article mainly introduces PHP socket programming in a simple way. This article explains in detail the relevant knowledge of socket and the package content of PHP socket programming examples. Friends in need can refer to

for TCP/IP and UDP. , Socket programming, these words are not unfamiliar to you, right? With the development of network technology, these words are flooding our ears. So I want to ask:

1. What are TCP/IP and UDP?
2.Where is Socket?
3.What is Socket?
4.Can you use them?

What are TCP/IP and UDP?

TCP/IP (Transmission Control Protocol/Internet Protocol) is an industrial standard protocol set designed for wide area networks (WANs).

UDP (User Data Protocol, User Datagram Protocol) is a protocol corresponding to TCP. It is a member of the TCP/IP protocol suite.

Here is a diagram showing the relationship between these protocols.

The TCP/IP protocol suite includes the transport layer, network layer, and link layer. Now you know the relationship between TCP/IP and UDP.

Where is Socket?

In Figure 1, we do not see the shadow of Socket, so where is it? Let’s let pictures speak for themselves.

It turns out that the Socket is here.

What is Socket?

Socket is an intermediate software abstraction layer for communication between the application layer and the TCP/IP protocol suite. It is a set of interfaces. In Design Pattern, 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 is everything, and let Socket organize it. data to comply with the specified protocol.

Will you use them?

Previous people have done a lot for us, and communication between networks has become much simpler, but after all, there is still a lot of work to be done. When I heard about Socket programming before, I thought it was relatively advanced programming knowledge, but as long as we understand the working principle of Socket programming, the mystery will be lifted.
A scene from life. If you want to call a friend, dial the number first. The friend will pick up the phone after hearing the ringing tone. At this time, you and your friend will be connected and you can talk. When the communication is over, hang up the phone to end the conversation. Scenes in life explain how this works. Maybe the TCP/IP protocol family was born in life, but this is not necessarily the case.

Let’s start with the server side. The server first initializes the Socket, then binds to the port, listens to the port, calls accept to block, and waits for the client to connect. At this time, if a client initializes a Socket and then 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 sends the response data to the client, the client reads the data, and finally closes the connection, and the interaction ends.

socket related functions:
---------------------------------- -------------------------------------------------- ----------
socket_accept() Accept a Socket connection
socket_bind() Bind the socket to an IP address and port
socket_clear_error() Clear the socket error or the last error Error code
socket_close() Closes a socket resource
socket_connect() Starts a socket connection
socket_create_listen() Opens a socket listening on the specified port
socket_create_pair() Generates a pair of indistinguishable sockets into one In the array
socket_create() generates a socket, which is equivalent to generating a socket data structure
socket_get_option() Gets the socket option
socket_getpeername() Gets the IP address of a remote similar host
socket_getsockname() Gets the local The IP address of the socket
socket_iovec_add() Adds a new vector to a scatter/aggregate array
socket_iovec_alloc() This function creates an iovec data structure capable of sending, receiving, reading and writing
socket_iovec_delete() Delete an already 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() Gets the last error of the current socket Code
socket_listen() Listens to all connections from the specified socket
socket_read() Reads data of the specified length
socket_readv() Reads data from the scatter/aggregate array
socket_recv() From socket End the data to the cache
socket_recvfrom() Accept data from the specified socket, if not specified, the current socket will be defaulted
socket_recvmsg() Receive messages from iovec
socket_select() Multiple 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() Set it in the socket to Block mode
socket_set_nonblock() Set the socket to non-block mode
socket_set_option() Set the socket option
socket_shutdown() This function allows you to close reading, writing, or the specified socket
socket_strerror() Return Detailed error of specified error number
socket_write() Write data to socket cache
socket_writev() Write data to scatter/aggregate array

Case 1: Socket communication demonstration

Server side :

<?php
//确保在连接客户端时不会超时
set_time_limit(0);

$ip = &#39;127.0.0.1&#39;;
$port = 1935;

/*
 +-------------------------------
 *  @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() 失败的原因是:".socket_strerror($sock)."\n";
}

if(($ret = socket_bind($sock,$ip,$port)) < 0) {
  echo "socket_bind() 失败的原因是:".socket_strerror($ret)."\n";
}

if(($ret = socket_listen($sock,4)) < 0) {
  echo "socket_listen() 失败的原因是:".socket_strerror($ret)."\n";
}

$count = 0;

do {
  if (($msgsock = socket_accept($sock)) < 0) {
    echo "socket_accept() failed: reason: " . socket_strerror($msgsock) . "\n";
    break;
  } else {
    
    //发到客户端
    $msg ="测试成功!\n";
    socket_write($msgsock, $msg, strlen($msg));
    
    echo "测试成功了啊\n";
    $buf = socket_read($msgsock,8192);
    
    
    $talkback = "收到的信息:$buf\n";
    echo $talkback;
    
    if(++$count >= 5){
      break;
    };
    
  
  }
  //echo $buf;
  socket_close($msgsock);

} while (true);

socket_close($sock);
?>

This is the server code of the socket. Then run cmd, pay attention to the storage path of your own program.

No response, the server program has started running and the port has started listening. Run netstat -ano to check the port status. Mine is port 1935

. Look, the port is already in the LISTENING state. Next we only need to run the client program to connect. Upload the code

<?php
error_reporting(E_ALL);
set_time_limit(0);
echo "<h2 id="TCP-IP-nbsp-Connection">TCP/IP Connection</h2>\n";

$port = 1935;
$ip = "127.0.0.1";

/*
 +-------------------------------
 *  @socket连接整个过程
 +-------------------------------
 *  @socket_create
 *  @socket_connect
 *  @socket_write
 *  @socket_read
 *  @socket_close
 +--------------------------------
 */

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket < 0) {
  echo "socket_create() failed: reason: " . socket_strerror($socket) . "\n";
}else {
  echo "OK.\n";
}

echo "试图连接 &#39;$ip&#39; 端口 &#39;$port&#39;...\n";
$result = socket_connect($socket, $ip, $port);
if ($result < 0) {
  echo "socket_connect() failed.\nReason: ($result) " . socket_strerror($result) . "\n";
}else {
  echo "连接OK\n";
}

$in = "Ho\r\n";
$in .= "first blood\r\n";
$out = &#39;&#39;;

if(!socket_write($socket, $in, strlen($in))) {
  echo "socket_write() failed: reason: " . socket_strerror($socket) . "\n";
}else {
  echo "发送到服务器信息成功!\n";
  echo "发送的内容为:<font color=&#39;red&#39;>$in</font> <br>";
}

while($out = socket_read($socket, 8192)) {
  echo "接收服务器回传信息成功!\n";
  echo "接受的内容为:",$out;
}


echo "关闭SOCKET...\n";
socket_close($socket);
echo "关闭OK\n";
?>

So far the client has connected to the server.

Case 2: Detailed code explanation

// 设置一些基本的变量
$host = "192.168.1.99";
$port = 1234;
// 设置超时时间
set_time_limit(0);
// 创建一个Socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not createsocket\n");
//绑定Socket到端口
$result = socket_bind($socket, $host, $port) or die("Could not bind tosocket\n");
// 开始监听链接
$result = socket_listen($socket, 3) or die("Could not set up socketlistener\n");
// accept incoming connections
// 另一个Socket来处理通信
$spawn = socket_accept($socket) or die("Could not accept incomingconnection\n");
// 获得客户端的输入
$input = socket_read($spawn, 1024) or die("Could not read input\n");
// 清空输入字符串
$input = trim($input);
//处理客户端输入并返回结果
$output = strrev($input) . "\n";
socket_write($spawn, $output, strlen ($output)) or die("Could not write
output\n");
// 关闭sockets
socket_close($spawn);
socket_close($socket);

The following is a detailed description of each step:

1. The first step is to establish two variables to save the server where the Socket is running. IP address and port. You can set it to your own server and port (this port can be a number between 1 and 65535), provided that this port is not in use.

The code is as follows:

// 设置两个变量
$host = "192.168.1.99";
$port = 1234;

2. You can use the set_time_out() function on the server side to ensure that PHP will not time out while waiting for the client to connect.

The code is as follows:

// 超时时间
set_time_limit(0);

3. Based on the previous ones, it is time to create a Socket using the socket_creat() function - this function returns a Socket handle, which will be used in all subsequent functions.

The code is as follows:

// 创建Socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create
socket\n");

The first parameter "AF_INET" is used to specify the domain name;
The second parameter "SOCK_STREM" tells the function what type of Socket will be created (in this example it is TCP type)

Therefore, if you want to create a UDP Socket, you can use the following code:

The code is as follows:

// 创建 socket
$socket = socket_create(AF_INET, SOCK_DGRAM, 0) or die("Could not create
socket\n");

4. Once a Socket is created handle, the next step is to specify or bind it to the specified address and port. This can be done through the socket_bind() function.

The code is as follows:

// 绑定 socket to 指定地址和端口
$result = socket_bind($socket, $host, $port) or die("Could not bind to
socket\n");

5. When the Socket is created After binding to a port, you can start listening for external connections. PHP allows you to start a listening through the socket_listen() function, and you can specify a number (in this example, the second parameter: 3)

The code is as follows:

// 开始监听连接
$result = socket_listen($socket, 3) or die("Could not set up socket
listener\n");

6. Up to now, your server has basically done nothing except waiting for a connection request from the client. Once a client connection is received, socket_accept() The function starts to work. It receives the connection request and calls another sub-Socket to process the information between the client and the server.

 代码如下:

//接受请求链接
// 调用子socket 处理信息
$spawn = socket_accept($socket) or die("Could not accept incoming
connection\n");

这个子socket现在就可以被随后的客户端–服务器通信所用了.

7.当一个连接被建立后,服务器就会等待客户端发送一些输入信息,这写信息可以由socket_read()函数来获得,并把它赋值给PHP的$input变量.

 代码如下:

// 读取客户端输入
$input = socket_read($spawn, 1024) or die("Could not read input\n");
?>

socker_read的第而个参数用以指定读入的字节数,你可以通过它来限制从客户端获取数据的大小.

注意:socket_read函数会一直读取壳户端数据,直到遇见\n,\t或者\0字符.PHP脚本把这写字符看做是输入的结束符.

8.现在服务器必须处理这些由客户端发来是数据(在这个例子中的处理仅仅包含数据的输入和回传到客户端).这部分可以由socket_write()函数来完成(使得由通信socket发回一个数据流到客户端成为可能)

代码如下:

// 处理客户端输入并返回数据
$output = strrev($input) . "\n";
socket_write($spawn, $output, strlen ($output)) or die("Could not write
output\n");

9.一旦输出被返回到客户端,父/子socket都应通过socket_close()函数来终止

 代码如下:

// 关闭 sockets
socket_close($spawn);
socket_close($socket);

The above is the detailed content of What is php socket?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

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

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

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

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

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

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

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.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

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

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

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.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

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.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

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

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)