我正在尝试从文件index.php(服务器)向使用websockets连接的客户端发送消息。
我的用于创建客户端连接的JavaScript文件:
var websocket_server = new WebSocket("ws://localhost:4950/");
websocket_server.onopen = function(e) {
console.log("connected");
}
websocket_server.onmessage = function(e)
{
console.log('message received from server');
}
index.php:
$msg = "Message from server";
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("Could not create socket\n");
socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR,1) or die("prbl options\n");
socket_connect($sock, '127.0.0.1', 4950) or die("could not connect\n");
socket_write($sock, $msg, strlen($msg));
客户端成功连接到Websocket,但是当我运行PHP文件时,我什么也没收到(控制台中没有错误,也没有消息)。
换句话说,javascript不会将我的socket_write视为消息:/
有什么想法吗? :)
答案 0 :(得分:1)
由于@ADyson,我找到了解决方案;) 我现在正在使用SSE服务器发送的事件,它可以正常工作!但是我想知道我的代码是否“正确”,或者是否还有一种“适当的”方式。
我正在使用会话超全局变量将服务器信息更改传递到另一个文件,该文件不断将其读取为事件流(这是SSE的工作方式)。
index.php:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<script type="text/javascript" src="jquery.js">
</script>
<script type="text/javascript" src="stream.js">
</script>
</head>
<body>
<a>Receive message</a>
</body>
</html>
stream.js(侦听服务器):
var serv = new EventSource("server.php");
serv.onmessage = function(e) {
var jdata = JSON.parse(e.data);
console.log(jdata.message);
};
serv.onopen = function(e) {
console.log('Connection opened');
}
$(document).ready(function(){
$('a').click(function(){
receive_msg();
});
});
function receive_msg(){
$.ajax({
type: "POST",
url: 'controller.php',
data: {action: 'send'}
});
}
controller.php:
<?php
session_start();
if (isset($_POST['action'])) {
$_SESSION['server']="you have received a message";
}
server.php:
<?php
session_start();
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
if (isset($_SESSION['server'])) {
$data = array(
'message'=> $_SESSION['server']
);
$data = json_encode($data);
echo "data: {$data}\n\n";
unset($_SESSION['server']);
}
工作方式:
客户端连接到server.php并不断读取文件。当服务器要向客户端发送消息时,它将创建一个会话变量。 Server.php读取变量并将其传递给我的js文件。然后变量被销毁,因此我们只传递一次消息。