我使用PHP创建了一个套接字服务器,代码如下
function listen()
{
// set some variables
$host = "127.0.0.1";
$port = 25003;
// don't timeout!
set_time_limit(0);
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
// bind socket to port
$result = socket_bind($socket, $host, $port) or die("Could not bind to socket\n");
// start listening for connections
$result = socket_listen($socket, 3) or die("Could not set up socket listener\n");
// accept incoming connections
// spawn another socket to handle communication
$spawn = socket_accept($socket) or die("Could not accept incoming connection\n");
// read client input
$input = socket_read($spawn, 1024) or die("Could not read input\n");
// clean up input string
$input = trim($input);
echo "Client Message : " . $input."\n";
// reverse client input and send back
$output = strrev($input) . "\n";
socket_write($spawn, $output, strlen($output)) or die("Could not write output\n");
// close sockets
socket_close($spawn);
socket_close($socket);
listen();
}
set_time_limit(0);
listen();取自http://www.codeproject.com/Tips/418814/Socket-Programming-in-PHP
我使用Javascript创建客户端套接字,如下所示
Javascript
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function WebSocketTest()
{
if ("WebSocket" in window)
{
alert("WebSocket is supported by your Browser!");
// Let us open a web socket
var ws = new WebSocket("ws://localhost:25003");
ws.onopen = function()
{
// Web Socket is connected, send data using send()
ws.send("Message to send");
alert("Message is sent...");
};
ws.onmessage = function (evt)
{
var received_msg = evt.data;
alert("Message is received...");
};
ws.onclose = function()
{
// websocket is closed.
alert("Connection is closed...");
};
}
else
{
// The browser doesn't support WebSocket
alert("WebSocket NOT supported by your Browser!");
}
}
</script>
</head>
<body>
<div id="sse">
<a href="javascript:WebSocketTest()">Run WebSocket</a>
</div>
</body>
</html>然后我运行PHP服务器,这是工作,它在监听。我运行Javascript客户端,它的工作,PHP服务器正在接收来自Javascript的请求。
BUt来自PHP的响应如下

我不明白如何更改客户端消息,比方说我想发送像"Hello“这样的消息。如何从javascript调用它,使PHP服务器只接收"Hello”?2.任何人都可以向我解释这样的每个url的功能是什么?
ws://localhost:25003/daemon.php第二个参数是什么?这是否连接到我的php文件?因为我试图定位到我的php,所以它不起作用。
发布于 2016-03-19 04:54:44
PHP套接字服务器正常,问题是Javascript,它发送HTTP请求,这个发送是HTTP协议。
您可以在该端口上启动,并回答有关Ajax查询的请求。
命令行,以像Web服务器一样启动php
php -S 127.0.0.1:25003WebServer的文档根对于PHP是相同的。
https://stackoverflow.com/questions/36097839
复制相似问题