简体   繁体   English

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

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

If we create a socket in server side then it runs in a infinite loop, cant we do something like this for the client side? 如果我们在服务器端创建一个套接字,那么它会无限循环地运行,我们不能为客户端做这样的事情吗? Can we create a listening mood in a infinite loop? 我们可以无限循环地营造倾听情绪吗? Do I need to create a new socket every for this every time? 我是否每次都需要为此创建一个新的套接字?

Here is my code, it writes only once, when I try to write after socket_read it doesn't work. 这是我的代码,只写一次,当我尝试在socket_read之后写时,它不起作用。

Server side code 服务器端代码

<?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);
?>

client side code 客户端代码

<?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);
?>

If we create a socket in server side then it runs in a infinite loop, cant we do something like this for the client side? 如果我们在服务器端创建一个套接字,那么它会无限循环地运行,我们不能为客户端做这样的事情吗? Can we create a listening mood in a infinite loop? 我们可以无限循环地营造倾听情绪吗?

Of course - if your server and client would send and receive strictly in turn, you could simply change the socket_read line in the client to 当然-如果您的服务器和客户端严格按顺序发送和接收,则只需将客户端中socket_read行更改为

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

Do I need to create a new socket every for this every time? 我是否每次都需要为此创建一个新的套接字?

No, you must not, since it wouldn't be the same connection. 不,您一定不能,因为它不会是同一连接。

But for a more complete server example which handles multiple connections and disconnections, cf. 但对于处理多个连接和断开连接的更完整的服务器示例,请参见。 this answer to How to write server for chat program in php by using socket . 这个答案 如何使用套接字为php中的聊天程序编写服务器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM