【问题标题】:Creating a client and server side socket connection and keeping it connected in php创建客户端和服务器端套接字连接并在 php 中保持连接
【发布时间】:2015-12-29 14:35:39
【问题描述】:

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

这是我的代码,它只写一次,当我尝试在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);
?>

【问题讨论】:

  • 你可以在编程中做任何你想做的事情。您可以创建一个始终连接的客户端。问题是 - 它是否有意义,您为什么想要或需要这样做?
  • 我正在制作一个 android 聊天应用程序,我想继续列出服务器和客户端传入的 cammand
  • 然后呢?问题出在哪里?
  • 问题是套接字写入只能工作一次......当我尝试在 socket_read() id 不起作用后写入时
  • 如果您的客户端处于无限循环中,它如何知道要发送哪些消息?你的客户的作案手法是什么?有一些细节缺失。有没有机会看看 IRC 协议?在我看来,这就是你所追求的,并且有很多例子,在 PHP 和 JavaScript 中,关于如何实现它和创建一个聊天应用程序。

标签: php sockets


【解决方案1】:

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

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

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

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

不,你不能,因为它不会是同一个连接。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-04
    • 1970-01-01
    • 2017-02-25
    • 2021-03-31
    • 2016-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多