简体   繁体   English

在连接时从客户端发出socket.io消息

[英]emitting socket.io message from the client side upon connection

I have this code running from my javascript client side. 我从我的javascript客户端运行此代码。

var num = Math.floor((Math.random() * 1000 + 1));

var socket = io();

io.on('connection', function(socket){
    socket.emit('random_number',num);
});

the 'random_number' never makes it to the server. 'random_number'永远不会进入服务器。 A few second later I can emit messages successfully and they reach the server.... but just not the initial message upon connection. 几秒钟后,我可以成功发出消息,它们到达服务器.....但是连接时不是初始消息。

What am I doing wrong? 我究竟做错了什么?

io.on('connection', function(socket){
    socket.emit('random_number',num);
});

The 'connection' event is in the server API, for the client it's 'connect' : 服务器服务器API中的'connection'事件是客户端的'connect'

io.on('connect', function(socket){
    socket.emit('random_number',num);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM