我有一个基本的聊天室,可以检测用户何时连接到服务器,然后离开。
现在我想提示用户在加入服务器时输入用户名,我该怎么做?
代码如下:
的index.html
<html>
<head>
<script src="http://localhost:3000/socket.io/socket.io.js"></script>
<script type="text/javascript" charset="utf-8">
var socket = io.connect('http://localhost:3000');
socket.on('entrance', function (data) {
document.write('<p>' + data.message + '</p>');
//STORE USERNAME of NEW SOCKET
// on connection to server, ask for user's name with an anonymous callback
socket.on('connect', function(){
// call the server-side function 'adduser' and send one parameter (value of prompt)
socket.emit('adduser', prompt("What's your name?"));
});
});
socket.on('exit', function (data) {
document.write('<p>' + data.message + '</p>');
});
socket.on('chat', function (data) {
document.write('<p>' + data.message + '</p>');
});
</script>
</head>
<body>
</body>
</html>
Server.js
var io = require('socket.io'),
connect = require('connect');
var app = connect().use(connect.static('public')).listen(3000);
var game_room = io.listen(app);
game_room.sockets.on('connection', function (socket) {
socket.emit('entrance', {message: 'Welcome to the chat room!'});
socket.emit('entrance', {message: 'Your ID is #' + socket.id});
socket.on('disconnect', function () {
game_room.sockets.emit('exit', {message: 'A chatter has disconnected.'});
});
socket.on('chat', function (data) {
game_room.socket.broadcast.emit('chat', {message: '# ' + data.message});
});
socket.broadcast.emit('entrance', {message: 'A new chatter is online.'});
});
答案 0 :(得分:1)
您可以将其添加到您的服务器代码中:
var users = [];
game_room.sockets.on('connection', function (socket) {
socket.emit('entrance', {message: 'Welcome to the chat room!'});
socket.emit('entrance', {message: 'Your ID is #' + socket.id});
socket.on('adduser', function (name) {
users.push(name);
// attempt to clean up
socket.once('disconnect', function () {
var pos = users.indexOf(name);
if (pos >= 0)
users.splice(pos, 1);
});
});
// ...
});
(如果2个用户选择相同的名称,则无效。)
答案 1 :(得分:0)
server.js
io.on('connection', function(socket){
socket.on('newuser', function(nick){
var newUser = nick;
console.log(newUser + ' connected');
io.emit('connection2', newUser + ' connected.');
socket.on('disconnect', function(){
console.log('user disconnected');
io.emit('disconnection', newUser + ' disconnected.');
});
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});
index.html
- 在&lt; script&gt;中标签var socket = io();
var nick = prompt('What is your desired username?');
$(function () {
var socket = io();
socket.emit('newuser', nick);
// Regular forum submission event handler below this.
});
socket.on('connection2', function(msg){
$('#messages').append($('<li style="font-style:italic;">').text(msg));
});
socket.on('disconnection', function(msg){
$('#messages').append($('<li style="font-style:italic;">').text(msg));
});