Detailed introduction to php Socket programming

怪我咯
Release: 2023-03-13 16:48:01
Original
2629 people have browsed it

PHP uses Berkeley's socket library to create its connection. You can know that socket is just a data structure. You use this socket data structure to start a session between the client and the server. This server is always listening and preparing to generate a new session. When a client connects to the server, it opens a port on which the server is listening for a session. At this time, the server accepts the client's connection request, and then performs a loop. Now the client can send information to the server, and the server can send information to the client.
To generate a Socket, you need three variables: a protocol, a socket type and a public protocol type. There are three protocols to choose from when generating a socket. Continue reading below to get detailed protocol content.
Defining a public protocol type is an essential element for connection

Let us start with a simple example --- a string that receives input characters , processes and Return this string to the client's TCP service. The code is as follows:

<?php
// 设置一些基本的变量 
$host = "192.168.1.99"; 
$port = 1234; 
// 设置超时时间 
set_time_limit(0); 
// 创建一个Socket 
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create 
socket\n"); 
//绑定Socket到端口 
$result = socket_bind($socket, $host, $port) or die("Could not bind to 
socket\n"); 
// 开始监听链接 
$result = socket_listen($socket, 3) or die("Could not set up socket 
listener\n"); 
// accept incoming connections 
// 另一个Socket来处理通信 
$spawn = socket_accept($socket) or die("Could not accept incoming 
connection\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); 
?>
Copy after login

The above is the detailed content of Detailed introduction to php Socket programming. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!