客户端代码:-
<script src="/socket.io/socket.io.js"></script>
...snip...
var socket = io.connect( 'http://localhost:5000' );
socket.on('text_msg', function (data) {
socket.emit('message', {txt:"test"}); //this is not working
alert( data.msg );
});
服务器端代码如下:-
const io = require('socket.io').listen(5000);
io.emit('text_msg', {msg: 'Welcome you are now connected.'}); //this is working good
// plain message - this never works
io.on('message', function(data){
console.log("message : " + data.txt); //No msg on console!
});
});
请帮助我从客户端脚本向服务器发送消息。
答案 0 :(得分:0)
您在启动套接字服务器时发出了text_msg事件,而不是在建立连接时发出。您应该在服务器上监听连接事件,然后向连接的套接字发出欢迎消息。
也不会看到客户端发送到服务器的消息,因为您没有在听。您需要在每个单独的套接字上进行监听。
您的服务器端代码应如下所示:
const io = require('socket.io').listen(5000);
io.on('connection', function (socket) {
socket.emit('text_msg', {
msg: 'Welcome you are now connected.'
});
socket.on('message', function(data) {
console.log('message : ' + data.txt);
});
});