我有一个 Nodejs 项目
但是socket.io连接它为时已晚。
它第一次打开,socket.io 没有连接。Socket.io 几乎在 10-15 秒后连接。
我的服务器 JS:
var io = require('socket.io').listen(8080);
function getUsernames(room) {
var clients = io.sockets.clients(room);
client=new Array();
clients.forEach(function(_client) {
client.push({username:_client.username,room:_client.room})
});
return client;
}
io.sockets.on('connection', function(client){
client.on('login', function(username, room){
client.username = username;
client.room = room;
client.join(client.room);
io.sockets.to(client.room).emit('updateuser', getUsernames(client.room));
});
client.on('mesajgonder', function(data){
client.emit('mesajgitti', data)
client.broadcast.emit('mesajgitti', data)
});
client.on('disconnect', function(){
var eskiroom = client.room;
client.leave(client.room);
io.sockets.to(eskiroom).emit('updateuser', getUsernames(eskiroom));
});
});
我的客户 JS:
var socket;
var room = 'room8';
var username = 'username';
var socket = io.connect("http://localhost:8080");
$(".text_metin").append('<span><p>Welcome to</p> <b>`'+room+'`</b> write now!</span>');
socket.on('connect', function(s){
socket.emit('login', username, room);
socket.on("mesajgitti", function(data){
$(".text_metin").append("<li id='chat_metin'>" + data.mesaj + "</li>");
});
socket.on('updateuser', function(users){
$.each(users, function(i, user) {
$("#user_liste").empty();
$("#user_liste").append('<li><img src="images/1111.png" alt="" width="20" height="20" /><a href="#" title="Coming Soon">'+user.username+'</a></li>');
});
});
});
$("#mesajGonder").click(function(){
var mesaj = $("#writechat").val();
if (!mesaj){
return;
}
socket.emit('mesajgonder',{
'mesaj' : mesaj,
});
$("#mesajinput").val("");
});
$(".tags li a").click(function(){
var demo = $(this).text();
$("#interested").val($("#interested").val()+','+demo);
});
$("#mesajGonder").click(function(){
$("#writechat").val('');
});
我不使用快递。谢谢你