【发布时间】: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 中,关于如何实现它和创建一个聊天应用程序。