【发布时间】:2021-09-01 20:59:54
【问题描述】:
我有一个 twig 模板,我正在尝试在 url 中发送具有相同令牌的消息意味着从 http://url/{token1} 发送的消息只能由具有相同令牌的另一个 url 接收。
但我无法将任何消息从 twig 传递到 node 到 symfony。
index.html.twig
<div id="chat">
</div>
<div>
<div class="form-group">
<label for="name">Name:</label> <input type="text" id="name">
</div>
<div class="form-group">
<label for="message">Message:</label> <input type="text" id="message">
</div>
<button type="button" id="sendBtn" class="btn-primary">Send</button>
</div>
<script src="/bin/ws-broker.js"></script>
<script>
const socket = new WebSocket("ws://localhost:8080");
document.getElementById("sendBtn").addEventListener("click", function() {
const message = {
name: document.getElementById("name").value,
message: document.getElementById("message").value
};
socket.send(JSON.stringify(message));
});
</script>
/bin/ws-broker.js
const WebSocket = require('ws');
const qs = require('querystring');
const wss = new WebSocket.Server({ port: 8080 });
const http = require('http');
wss.on('connection', function connection(ws, req)
{
console.log('Connection Received from IP: ' + req.socket.remoteAddress);
ws.on('message', function incoming(message) {
if ('' === message) {
//empty message
return;
}
try {
//process message as JSON object
message = JSON.parse(message);
} catch (e) {
//failed parsing the message as JSON
return;
}
});
});
console.log('Listening on port 8080');
控制器
/**
* @Route("/{token}", name="home")
*/
public function index(): Response
{
return $this->render('home/index.html.twig', [
'controller_name' => 'HomeController',
]);
}
【问题讨论】:
-
我提供的
/bin/ws-broker.js根本不打算放在前端。它必须通过后端的 nodejs 作为服务器运行。例如:node bin/ws-broker.js替换symfony bin/console --env=prod app:command -
有很多东西可能会阻止 websockets。仅此页面就列出了十几个:support.grammarly.com/hc/en-us/articles/…。建议:1)首先关注您的开发环境。编写一对简单的“hello world”应用程序只是为了验证您可以将消息从客户端发送到服务器。 2)然后从那里扩大你的范围。 3) 一旦您对 end::end 通信在您的开发环境中工作感到满意,请在更“现实”的环境中进行测试。
-
@Will B. 是的,我已经启动了节点
-
token来自哪里?它需要从客户端 javascript 发送到节点 websocket 侦听器bin/ws-broker.js。客户应该如何处理响应? -
这是一个相同的问题,不是后续问题:How to arguments into the Websocket handler?
标签: php node.js websocket symfony4