[英]Socket.io question - how does the client and server communicate
我刚刚开始使用 socket.io。 我正在浏览网页中提到的示例。 特别是下面的服务器代码
io.on('connection', function(socket){
socket.on('nitrous', function(msg){
io.emit('nitrous', msg);
console.log( "Server is emiting the event");
});
});
结合下面的客户端代码
<script src="/socket.io/socket.io.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(function () {
var socket = io();
$('form').submit(function(e){
e.preventDefault(); // prevents page reloading
socket.emit('nitrous', $('#m').val());
$('#m').val('');
return false;
});
socket.on('nitrous', function(msg){
$('#messages').append($('<li>').text(msg));
console.log( "Client is emiting the event");
});
});
</script>
我知道我们提交了表单,它会发出一个名为“nitrous”的事件,然后将调用在套接字上注册的处理程序。 但我也注意到服务器上的套接字对象上的处理程序也被调用了。 我的第一个问题是连接到应用程序的所有用户如何发生这种情况。 其次,在服务器中,有一个具有相同事件名称的 io.emit() 正在传递 - 如何以及在哪里处理? 我没有包含任何 io.on() 但它仍然有效。
我指的是这个例子: https : //socket.io/get-started/chat/#Integrating-Socket-IO
请分享您对此的看法。
谢谢,帕万。
让我重写你的代码来解释发生了什么:
// Server
// when server gets new client connected do this:
serverSocket.on('connection', function (client) {
// when server receives event from client that called "nitrous" do this:
client.on('nitrous', function (msg) {
// emit event with name "nitrous" to every client - including sender
serverSocket.emit('nitrous', msg)
// or could just emit event to everyone but sender
// client.broadcast.emit('nitrous') // uncomment this line
console.log('Server receives the event from client')
})
})
现在客户端(仅 javascript):
// Client
$(function () {
const clientSocket = io()
$('form').submit(function (e) {
e.preventDefault() // prevents page reloading
// message that client wants to send
const msg = $('#m').val()
// emit event called "nitrous" to server
clientSocket.emit('nitrous', msg)
// clear input field
$('#m').val('')
return false
});
// when client receives event from server called 'nitrous' do this:
clientSocket.on('nitrous', function (msg) {
// append LI element to list of messages
$('#messages').append($('<li>').text(msg))
console.log('Client receives the event')
})
})
希望这更有意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.