[英]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.