Home Backend Development PHP Tutorial How to connect socket socket in PHP

How to connect socket socket in PHP

Apr 22, 2019 am 11:14 AM
php socket

Socket is usually also called "socket", which is used to describe the IP address and port. It is the handle of a communication chain. Applications usually make requests to the server or respond to network requests through "sockets". This article mainly talks about the connection process between socket characters in PHP, which has certain reference value. Interested friends can learn about it.

Depending on how the link is started and the target to which the local socket is connected, the connection process between sockets can be divided into three steps:

1. Server monitoring: The server-side socket does not locate the specific client socket, but is in a state of waiting for connection and monitors the network status in real time.

2. Client request: refers to a connection request made by the client's socket, and the target to be connected is the server's socket. To do this, the client's socket must first familiarize itself with the server's socket to which it wants to connect, indicate the address and port number of the server's socket, and then make a connection request just like the server's socket.

3. Connection confirmation: means that when the server-side socket listens or receives the connection request of the client socket, it responds to the request of the client socket. , create a new thread and send the description of the server-side socket to the client. Once the client confirms this description, the connection is established. The server-side socket continues to be in the listening state and continues to receive link requests from other client sockets.

1. Test environment:

Server ip: xxx.xxx.xxx.1

# # Client ip: xxx.xxx.xxx.2

2. Test process:

The client server will be on this machine (xxx .xxx.xxx.1) Send data to the socket server of the server (xxx.xxx.xxx.2) through socket. After receiving the data sent by the client, the server returns some data to the client.

3. Server file content: 

<?php
  //获取tcp协议号吗.
  $tcp = getprotobyname("tcp");
  //建立server端socket , 创建并返回一个套接字,也称做一个通讯节点.一个典型的网络连接由2个套接字构成 , 一个运行在客户端 , 另一个运行在服务器端.
  $socket = socket_create(AF_INFT , SOCK_STREAM , $tcp);
  //绑定要监听的ip和端口 , 这里绑定的ip一定要写局域网ip , 写成127.0.0.1客户端将无法与服务器端建议连接.
  socket_bind($socket , &#39;xxx.xxx.xxx.1&#39; , 10008);
  //监听端口
  socket_listen($socket);
  //初始化一个数据 , 和客户端通信
  $buffer = "connect";
  while(true){
    //接受客户端请求过来的yigesocket连接
    $connection = socket-accept($scoket);
    if(!connection){
      echo "connect faild";
    } else {
    echo "Socket connected \n";
    //向客户传递一个信息数据
   if($buffer != ""){
    echo "send data to client\n";
    socket_write($connection , $buffer , "\n");
    echo "Wrote to socket\n";    
} else {
    echo "no data in the buffer\n";
}   
  //从客户端获取得的数据
  while($data = $socket_read($connection , 1024 , PHP_NORMAL_READ)){
  printf("Buffer:".$data.&#39;\n&#39;);
  //取得信息给客户端一个反馈 ,Thank you client , you data is Received success发给客户端的回应信息.
  socket-wirte($coennection , "Thank you client , you data is Received success \n");
}
}
//关闭sockket
socket_close($connection);
printf("Closed the socket\n");
  
  }
?>
Copy after login

4. Client file content:

<?php
  //建立客户端的socket连接
  $socket = se);
  //连接服务器端socket
  $connection = socket_connect($socket , &#39;xxx.xxx.xxx.1&#39; , 10008);
  //要求发送到服务端的信息.
  $send_data = "This data will Send to server!";
  //客户端去连接服务端并接受服务端返回的数据 , 如果返回的数据保护not connect就提示不能连接.
  while($buffer = @socket_read($socket , 1024,PHP_NORMAL_READ)){
    if(preg_match("/not connect/" , $buffer)){
    echo "don&#39;t connect\n";
    break;
  } else {
  //服务端传来的信息
  echo "Buffer Data: ".$buffer .&#39;\n&#39;;
  echo "Writing to Socket\n";
  //将客户的信息写道通道中 , 传给服务器端
  if(!socket_write($socket , "$send_data\n")){
     echo "Write failed\n";
  }
  //服务器端收到信息后 , 客户端接受服务端传给客户端的回应信息.
  while($buffer = socket_read($socket , 1024 , PHP_NORMAL_READ)){
    echo "send to server: $send-data\n response from server was:".$buffer."\n";
  }
  }
  }
?>
Copy after login

5. Start the process on the server socket service.

#/usr/local/php/bin/php -a/home/server.php
Interactive mode enable 互动模式启动
Copy after login

6. After the server is started, check the started process and port

#netstat -tnlp |grep 10008
tcp   0  0 192.168.13:10008  0.0.0.0:*  LISTEN
28892/php
Copy after login

7. Perform transmission on the client (192.168.1.2)

#/usr/local/php/bin/php -a client.php
Interactive mode enabled
Copy after login

8. Return to the server to view acceptance information arrived.

#/usr/local/php/bin/php -a /home/server.php
Interactive mode enabled
 
Socket connected
send data client
Wrote to socket
Buffer:This data will Send to server!
Copy after login

Related tutorials:

PHP video tutorial

The above is the detailed content of How to connect socket socket in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

See all articles