我试图用socket.io在线显示所有用户名: 这是服务器端代码:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
var send="dsf";
var usernames=[];
var users=0;
io.on('connection', function(socket){
users++;
console.log(users);
io.emit("online",users);
socket.on("new",function(username)
{
console.log(username+"is connected");
socket.username=username;
usernames[username]=username;
console.log(usernames);
io.emit("users",
{total: users,
names:usernames});
}
);
socket.on('disconnect' ,function(){
users--;
console.log(users);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
这是客户方:
<script>
var socket = io();
$(document).ready(function(){
var name=prompt("What is your name?","");
if (name!="")
{
socket.emit("new",name);
}
socket.on("online",function(users)
{
alert(users);
})
socket.on("users",function(usernames)
{
alert(usernames.names.length);
});
});
</script>
我想要的只是在用户登录时显示所有连接的用户名。我无法发送包含所有连接用户名的用户名数组(我知道我必须在断开连接时删除用户,但我会在结束)
答案 0 :(得分:0)
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
$(document).ready(function(){
var name=prompt("What is your name?","");
if (name!="")
{
socket.emit("new",name);
}
socket.on("online",function(users)
{
alert(users);
})
socket.on("users",function(usernames)
{
alert(usernames.names.length);
});
});
</script>
<title>Socket.IO chat</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
</style>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
</body>
</html>
</html>
</html>
&#13;
答案 1 :(得分:0)
您需要更改usernames
数组分配,
usernames[username]=username;
要,
usernames.push(username);
将解决此问题。我测试过这个并且工作正常。
希望这有帮助!
答案 2 :(得分:0)
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
var send="dsf";
var usernames=[];
var users=0;
io.on('connection', function(socket){
users++;
console.log(users);
io.emit("online",users);
socket.on("new",function(username)
{
console.log(username+"is connected");
socket.username=username;
usernames.push(username);
console.log(usernames);
}
);
socket.on('disconnect' ,function(){
users--;
console.log(users);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});