search
HomeBackend DevelopmentPHP TutorialDetailed explanation of socket usage in php
Detailed explanation of socket usage in phpMay 30, 2018 pm 04:09 PM
phpsocketusage

The original English meaning of socket is "hole" or "socket". As the process communication mechanism of BSD UNIX, the latter meaning is taken. Used to describe IP addresses and ports, and is the handle of a communication chain. Hosts on the Internet generally run multiple service software and provide several services at the same time. Each service opens a Socket and binds it to a port. Different ports correspond to different services

PHP socket programming is relatively difficult to understand. However, we only need to understand a few socket functions It shouldn’t be difficult to understand the relationship between them and the roles they play. In the author’s opinion, socket programming is actually about establishing a client and server for a network service, which is similar to the client and service of mysql. The client and server are the same. As long as you understand what the client and server of MySQL are about, you should be able to understand what I am going to talk about below.

Regarding the network protocols involved in socket programming, such as TCP, UDP, socket three-way handshake, etc., there are very detailed explanations of these network protocols on the Internet. I will not go into them here. I will just cut a socket to create a socket. The process map of the connection is to let you see:

# This picture is what I have worked hard from others, you must look good, at the same time, here I am here I would also like to express my gratitude to the author whose screenshot was stolen from me. I apologize for stealing your pattern. I hope you don’t care about it. I am too lazy to draw pictures (actually it means I am not confident in my drawing skills, haha).

How does the socket establish a connection? As mentioned above, the process of establishing a connection is essentially the same as the connection between mysql client and server. The difference between it and mysql is that the server and client of mysql have been edited for us, we just need to apply it. However, the critical moment has come. Socket does not provide us with anything. The only thing it provides us is: dozens of socket functions.

The implication is that socket programming requires us to create the server and client ourselves. In other words, ``socket programming``--it requires us to create a server and client similar to mysql. terminal application.

Speaking of which, I would like to ask, do you think this socket is a headache? It neither creates a server nor a client for us to apply. We have to use the socket function ourselves and create our own network protocol socket application. Doesn't this give you a headache? There's nothing you can do about the headache. If you need your own application, you still have to deal with sockets. Haha, this is just a digression, I won’t say much, let’s get to the point.

Before you are confused by socket programming, I will let you take a look at several key functions of socket and explain their respective functions to you. Otherwise, if someone who has no foundation in socket programming reads this, I'm afraid that after reading it, you will decisively skip this article and develop a phobia about sockets from now on. Haha, I said more.

The key function of socket 1:

socket_create($net parameter 1, $stream parameter 2, $protocol parameter 3)

Function: Create a socket socket, To put it bluntly, it is a network data flow.

Return value: a socket, or false, an E_WARNING warning is issued for parameter errors

The PHP online manual makes it clearer:

socket_create creates and returns a Socket, also called a communication node. A typical network connection consists of 2 sockets, one running on the client side and the other running on the server side.

The above sentence is copied from the PHP online manual. Do you see that the meaning here is exactly the same as the client and server that I mentioned repeatedly above? hehe.

  Parameter 1 is: network protocol,

  What are the network protocols? Its options are the following three:

AF_INET: IPv4 network protocol. Both TCP and UDP can use this protocol. This is generally used, you know.

 AF_INET6: IPv6 network protocol. Both TCP and UDP can use this protocol.

AF_UNIX: Local communication protocol. High-performance and low-cost IPC (Inter-Process Communication).

Parameter 2: Socket stream, options are:

SOCK_STREAM SOCK_DGRAM SOCK_SEQPACKET SOCK_RAW SOCK_RDM.

Only the first two are explained here:

SOCK_STREAM TCP protocol socket.

  SOCK_DGRAM  UDP protocol socket.

For more information, please link here: http://php.net/manual/zh/function.socket-create.php

Parameter 3: protocol, options are:

SOL_TCP: TCP protocol.

SOL_UDP: UDP protocol.

It can be seen from here that the second parameter and the third parameter of the socket_create function are actually related.

For example, if your first parameter uses the IPv4 protocol: AF_INET, and then the second parameter uses the TCP socket: SOCK_STREAM,

Then the third parameter must be used SOL_TCP, this should not be difficult to understand.

As for TCP protocol sockets, of course you can only use the TCP protocol, right? If you use UDP sockets, I won’t say how to choose the third parameter, haha, you know.

Key function 2:

socket_connect($socket parameter 1, $ip parameter 2, $port parameter 3)

Function: connect a socket, the return value is true or false

Parameter 1: function return value of socket_create

Parameter 2: ip address

Parameter 3: Port number

Key function 3:

  socket_bind($socket parameter 1, $ip parameter 2, $port parameter 3)

   Function: Bind a socket, the return value is true or false

   Parameters 1: function return value of socket_create

Parameter 2: ip address

Parameter 3: Port number

Key function 4:

socket_listen($socket parameter 1,$backlog Parameter 2)

Function: Listen to a socket, the return value is true or false

Parameter 1: The function return value of socket_create

Parameter 2: Maximum number of listening sockets

Key function 5:

socket_accept($socket)

Function: Receive the resource information of the socket and return the socket successfully Information resources, failure is false

Parameters: function return value of socket_create

Key function 6:

socket_read($socket parameter 1, $length parameter 2)

Function: Read the resource information of the socket,

Return value: Successfully convert the socket resource into string information, failure is false

Parameter 1: socket_create or The function return value of socket_accept

Parameter 2: The length of the read string

Key function 7:

socket_write($socket parameter 1, $msg parameter 2, $ strlen parameter 3)

Function: Write data into the socket

Return value: Return the byte length of the string if successful, false

on failure Parameter 1: The function return value of socket_create or socket_accept

Parameter 2: String

Parameter 3: The length of the string

Key function 8:

socket_close($ socket)

Function: Close the socket

Return value: Return true on success, false on failure

Parameters: Function return value of socket_create or socket_accept

These eight functions are the core functions of socket. Here are two more important functions

socket_last_error($socket). The parameter is the return value of socket_create. Its function is to obtain the last error code of the socket. Number, return value socket code

  socket_strerror($code), the parameter is the return value of the socket_last_error function, obtain the string information of the code, the return value is the socket error information

These two functions are still very important in socket programming. When writing socket programming, I think you still have to make use of them, especially for novices. They can be used for debugging

  

   That’s the code, pay attention, please read my comments carefully, comments are very important, comments are very important, comments are very important, important things should be shouted three times, haha.

Server-side script, D:\vhost\test\socket\server_socket.php

<?php
//创建服务端的socket套接流,net协议为IPv4,protocol协议为TCP
$socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);

  /*绑定接收的套接流主机和端口,与客户端相对应*/
  if(socket_bind($socket,&#39;127.0.0.1&#39;,8888) == false){
    echo &#39;server bind fail:&#39;.socket_strerror(socket_last_error());
    /*这里的127.0.0.1是在本地主机测试,你如果有多台电脑,可以写IP地址*/
  }
  //监听套接流
  if(socket_listen($socket,4)==false){
    echo &#39;server listen fail:&#39;.socket_strerror(socket_last_error());
  }
//让服务器无限获取客户端传过来的信息
do{
  /*接收客户端传过来的信息*/
  $accept_resource = socket_accept($socket);
  /*socket_accept的作用就是接受socket_bind()所绑定的主机发过来的套接流*/

  if($accept_resource !== false){
    /*读取客户端传过来的资源,并转化为字符串*/
    $string = socket_read($accept_resource,1024);
    /*socket_read的作用就是读出socket_accept()的资源并把它转化为字符串*/

    echo &#39;server receive is :&#39;.$string.PHP_EOL;//PHP_EOL为php的换行预定义常量
    if($string != false){
      $return_client = &#39;server receive is : &#39;.$string.PHP_EOL;
      /*向socket_accept的套接流写入信息,也就是回馈信息给socket_bind()所绑定的主机客户端*/
      socket_write($accept_resource,$return_client,strlen($return_client));
      /*socket_write的作用是向socket_create的套接流写入信息,或者向socket_accept的套接流写入信息*/
    }else{
      echo &#39;socket_read is fail&#39;;
    }
  /*socket_close的作用是关闭socket_create()或者socket_accept()所建立的套接流*/
    socket_close($accept_resource);
  }
}while(true);
socket_close($socket);

Tip: Please note that the execution order of the three functions socket_bind, socket_listen, and socket_accept above cannot be changed. That is to say

  You must first execute socket_bind, then socket_listen, and finally execute socket_accept

Client script, D:\vhost\test\socket\client_socket.php

<?php
  //创建一个socket套接流
  $socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
  /****************设置socket连接选项,这两个步骤你可以省略*************/
   //接收套接流的最大超时时间1秒,后面是微秒单位超时时间,设置为零,表示不管它
  socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array("sec" => 1, "usec" => 0));
   //发送套接流的最大超时时间为6秒
  socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array("sec" => 6, "usec" => 0));
  /****************设置socket连接选项,这两个步骤你可以省略*************/

  //连接服务端的套接流,这一步就是使客户端与服务器端的套接流建立联系
  if(socket_connect($socket,&#39;127.0.0.1&#39;,8888) == false){
    echo &#39;connect fail massege:&#39;.socket_strerror(socket_last_error());
  }else{
    $message = &#39;l love you 我爱你 socket&#39;;
    //转为GBK编码,处理乱码问题,这要看你的编码情况而定,每个人的编码都不同
    $message = mb_convert_encoding($message,&#39;GBK&#39;,&#39;UTF-8&#39;);
    //向服务端写入字符串信息

    if(socket_write($socket,$message,strlen($message)) == false){
      echo &#39;fail to write&#39;.socket_strerror(socket_last_error());

    }else{
      echo &#39;client write success&#39;.PHP_EOL;
      //读取服务端返回来的套接流信息
      while($callback = socket_read($socket,1024)){
        echo &#39;server return message is:&#39;.PHP_EOL.$callback;
      }
    }
  }
  socket_close($socket);//工作完毕,关闭套接流

How to test these two scripts?

First, open the DOS window of Windows, which is the cmd black window. Then, run php D:\vhost\test\socket\server_socket.php,

Let the black window of the server continue to run. ,

Secondly, the php client script can be run through the browser, or you can open a cmd black window to run

  php D:\vhost\test\socket\client_socket.php

Please note here: the php running name must be added to the Windows environment variable. If you don’t know how to add it,

Please enter the php running command directory and run it with an absolute command. You can also use Baidu to add the php command Add it to the environment variable

This is my situation, your file address may be different from mine, please operate according to your address, otherwise, you will be responsible for the consequences, haha

As mentioned above, socket programming requires a server to communicate, so the black window on the server must be kept open.

Postscript:

socket_set_option($socket parameter 1, $level parameter 2, $optname parameter 3, $optval parameter 4)

The function of this function is to set The interface sets the data flow options, which is also a very important function.

Parameter 1: The function return value of socket_create or socket_accept

Parameter 2: SOL_SOCKET, it seems that this is the only option

Parameter 3 and parameter 4 are related,

Parameter 3 can be: SO_REUSEADDR SO_RCVTIMEO S0_SNDTIMEO

Explain:

SO_REUSEADDR It allows the socket port to be used again immediately after it is released

If parameter 3 is this, parameter 4 can be true or false

SO_RCVTIMEO It is the maximum timeout time of the socket's receiving resource

SO_SNDTIMEO It is the maximum timeout time of the socket's sending resource

If parameter 3 is these two, then parameter 4 is an array array('sec'=>1,'usec'=>500000)

Array They all set the maximum timeout time. However, one is in seconds and the other is in microseconds. They have the same effect.

The above is the entire content of this article. I hope it will be useful to everyone. Helps.


Related recommendations:

Detailed explanation of magic methods commonly used in PHP

##PHP Detailed explanation of how to use cookies in Chinese

PHP method to solve Chinese garbled characters

The above is the detailed content of Detailed explanation of socket usage in php. 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
Python的socket与socketserver怎么使用Python的socket与socketserver怎么使用May 28, 2023 pm 08:10 PM

一、基于TCP协议的socket套接字编程1、套接字工作流程先从服务器端说起。服务器端先初始化Socket,然后与端口绑定(bind),对端口进行监听(listen),调用accept阻塞,等待客户端连接。在这时如果有个客户端初始化一个Socket,然后连接服务器(connect),如果连接成功,这时客户端与服务器端的连接就建立了。客户端发送数据请求,服务器端接收请求并处理请求,然后把回应数据发送给客户端,客户端读取数据,最后关闭连接,一次交互结束,使用以下Python代码实现:importso

PHP+Socket系列之IO多路复用及实现web服务器PHP+Socket系列之IO多路复用及实现web服务器Feb 02, 2023 pm 01:43 PM

本篇文章给大家带来了关于php+socket的相关知识,其中主要介绍了IO多路复用,以及php+socket如何实现web服务器?感兴趣的朋友下面一起来看一下,希望对大家有帮助。

怎么使用Spring Boot+Vue实现Socket通知推送怎么使用Spring Boot+Vue实现Socket通知推送May 27, 2023 am 08:47 AM

SpringBoot端第一步,引入依赖首先我们需要引入WebSocket所需的依赖,以及处理输出格式的依赖com.alibabafastjson1.2.73org.springframework.bootspring-boot-starter-websocket第二步,创建WebSocket配置类importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Config

php socket无法连接怎么办php socket无法连接怎么办Nov 09, 2022 am 10:34 AM

php socket无法连接的解决办法:1、检查php是否开启socket扩展;2、打开php.ini文件,检查“php_sockets.dll”是否被加载;3、取消“php_sockets.dll”的注释状态即可。

php怎么设置implode没有分隔符php怎么设置implode没有分隔符Apr 18, 2022 pm 05:39 PM

在PHP中,可以利用implode()函数的第一个参数来设置没有分隔符,该函数的第一个参数用于规定数组元素之间放置的内容,默认是空字符串,也可将第一个参数设置为空,语法为“implode(数组)”或者“implode("",数组)”。

PHP+Socket系列之实现客户端与服务端数据传输PHP+Socket系列之实现客户端与服务端数据传输Feb 02, 2023 am 11:35 AM

本篇文章给大家带来了关于php+socket的相关知识,其中主要介绍了什么是socket?php+socket如何实现客户端与服务端数据传输?感兴趣的朋友下面一起来看一下,希望对大家有帮助。

利用PHP和Socket实现实时文件传输技术研究利用PHP和Socket实现实时文件传输技术研究Jun 28, 2023 am 09:11 AM

随着互联网的发展,文件传输成为人们日常工作和娱乐中不可或缺的一部分。然而,传统的文件传输方式如邮件附件或文件分享网站存在一定的限制,无法满足实时性和安全性的需求。因此,利用PHP和Socket技术实现实时文件传输成为了一种新的解决方案。本文将介绍利用PHP和Socket技术实现实时文件传输的技术原理、优点和应用场景,并通过具体案例来演示该技术的实现方法。技术

C#中常见的网络通信和安全性问题及解决方法C#中常见的网络通信和安全性问题及解决方法Oct 09, 2023 pm 09:21 PM

C#中常见的网络通信和安全性问题及解决方法在当今互联网时代,网络通信已经成为了软件开发中必不可少的一部分。在C#中,我们通常会遇到一些网络通信的问题,例如数据传输的安全性、网络连接的稳定性等。本文将针对C#中常见的网络通信和安全性问题进行详细讨论,并提供相应的解决方法和代码示例。一、网络通信问题网络连接中断:网络通信过程中,可能会出现网络连接的中断,这会导致

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

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

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment