创建客户端和服务器端套接字连接,并在php中保持连接


Creating a client and server side socket connection and keeping it connected in php

如果我们在服务器端创建一个套接字,那么它会在无限循环中运行,难道我们不能为客户端做这样的事情吗?我们能创造一种无限循环的聆听情绪吗?我需要每次为此创建一个新的套接字吗?

这是我的代码,它只写一次,当我尝试在socket_read之后写时,它不起作用。

服务器端代码

<?php
$host = "192.168.56.1";
$port = 8080;
$message = "Hello Client";
set_time_limit(0);
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket'n");
$result = socket_bind($socket, $host, $port) or die("Could not bind to socket'n");
$result = socket_listen($socket) or die("Could not set up socket listener'n");
echo 'listining ip '.$host." at port ".$port;
while(true){
$com = socket_accept($socket) or die("Could not accept incoming connection'n");
$input = socket_read($com, 1024) or die("Could not read input'n");
$input = trim($input);
echo '
Client says: '.$input;
socket_write($com, $message , strlen ($message)) or die("Could not write output'n");
}
echo '
server closed';
socket_close($com);
socket_close($socket);
?>

客户端代码

<?php
$host    = "192.168.56.1";
$port    = 8080;
$message = "Hello Server side";
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket'n");
$result = socket_connect($socket, $host, $port) or die ("Could not connect to server'n");
socket_write($socket, $message, strlen($message)) or die("Could not send data to server'n");
$result = socket_read($socket, 1024) or die("Could not read server response'n");
socket_write($socket,$message, strlen($message)) or die("Could not send data to server'n");
echo "Server  says :";//.$result;
socket_close($socket);
?>

如果我们在服务器端创建一个套接字,那么它将以无限循环运行,我们不能为客户做这样的事情吗?我们可以创建一个无限循环的聆听心情?

当然,如果您的服务器和客户端严格轮流发送和接收,您可以简单地将客户端中的socket_read行更改为

while ($result = socket_read($socket, 1024))

我需要每次为此创建一个新的套接字吗?

不,你一定不能,因为这不是同一个连接。

但是,对于处理多个连接和断开连接的更完整的服务器示例,请参阅如何使用socket在php中编写聊天程序服务器的答案。