我刚开始使用socket.io。我正在浏览网页中提到的示例。具体是
下的服务器代码[HttpPost("post-images")]
public async Task<IList<RepositoryItem>> PostAnImages ([FromForm]IList<PostRepoRequest> repositoryItems)
结合下面的客户代码
io.on('connection', function(socket){
socket.on('nitrous', function(msg){
io.emit('nitrous', msg);
console.log( "Server is emiting the event");
});
});
我了解我们提交了表单,它将发出一个名为“ nitrous”的事件,然后将调用在套接字上注册的处理程序。但是我也注意到服务器上套接字对象上的处理程序也被调用了。我的第一个问题是,对于连接到该应用程序的所有用户,这是怎么回事?其次,在服务器中,传递了具有相同事件名称的io.emit()-如何以及在何处处理?我没有包含任何io.on(),但仍然可以使用。
我指的是这个示例:https://socket.io/get-started/chat/#Integrating-Socket-IO
请分享您的想法。
谢谢, 帕万。
答案 0 :(得分:0)
让我重写您的代码以说明发生了什么事
// 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')
})
})
希望更有意义。