Node Chat program Instance 02:chat_server.js

Source: Internet
Author: User
Tags emit

Vousiu

Source: Http://www.cnblogs.com/vousiu

This example refers to the book "node. js in action" from Mike Cantelon and others.

Chat_server.js:

The client and server are constantly communicating through the Socket.io event:

Chat_server---------------> chat_ui

Chat_server <---------------chat_ui

In this paragraph:

    function () {      socket.emit (' rooms ', io.sockets.manager.rooms);    });

To register an asynchronous callback function:

<---------------' Rooms '------------------

|

'-------------' rooms '---------------> All rooms.

This code continuously refreshes the list of available rooms, in conjunction with the client's request for all room numbers to be timed. In fact, the user can open a new room and then broadcast to all users, so that there is no regular refresh. But in that case, the room will not disappear when the last user leaves the original room.

function assignguestname (socket, Guestnumber, nicknames, nameused) {  var name = ' Guest ' + guestnumber;    = name;  Socket.emit (' Nameresult ', {    true,    name:name  });  Nameused.push (name);   return Guestnumber + 1;}

Chat_server-----------' Nameresult '------------> {success:true, Name: ' Guestxxx '}

Updates the variables associated with name in the server.

(The user has not received the event message, the server continues to perform the following code operation is also OK, because the server here has stored the name of each user state, it is consistent.) )

I think the following three parameters do not need to pass, because they are the server local data, the transmission and non-transmission are the same, and this function is not an asynchronous function, is executed immediately. If it is an asynchronous function, it will result in an inconsistent situation.

functionJoinroom (socket, guest) {Socket.join (guest); Currentroom[socket.id]=the hostel ; Socket.emit (' Joinresult ', {room:room}); Socket.broadcast.to (Guest). Emit (' Message ', {text:nicknames[socket.id]+ ' has joined ' + + + '. '  }); varUsersinroom =io.sockets.clients (guest); if(Usersinroom.length > 1) {    varUsersinroomsummary = ' Users currently in ' + ' + ': ';  for(varIndexinchusersinroom) {      varUsersocketid =usersinroom[index].id; Usersinroomsummary+ Nicknames[usersocketid] + "; }} socket.emit (' Message ', {text:usersinroomsummary});}

Updates the local variables associated with the home.

Add the current socket's user to the socket's ' Roomname ' group.

Chat_server-----------' Joinresult '------------> {: ' Roomname '}

Chat_server---------(broadcast) ' message '----------> {text: ' Current user name has joined Roomname. '}

Why is the socket broadcast instead of IO? )

Get all the names in the room in sync.

Chat_server-----------' message '------------> {text: ' All names in Room '}

function handlemessagebroadcasting (socket) {  Socket.on(function(message) {    Socket.broadcast.to (Message.room). Emit (' message ', {      + ': ' + message.text    })   ;}

Registers an asynchronous callback function.

<---------------' message '------------------message

|

'-------------(broadcast:message.room) ' message '---------------> {text: ' Nickname:message '}

functionhandlenamechangeattempts (socket, nicknames, nameused) {Socket.on (' Nameattempt ',function(name) {if(Name.indexof (' guest ') = = 0) {Socket.emit (' Nameresult ', {success:false, message:' Name cant begin with Guest '      }); } Else {    if(Nameused.indexof (name) = =-1) {      varPreviousname =Nicknames[socket.id]; varPreviousnameindex =Nameused.indexof (previousname);      Nameused.push (name); Nicknames[socket.id]=name; DeleteNameused[previousnameindex]; Socket.emit (' Nameresult ', {success:true, name:name}); } Else{socket.emit (' Nameresult ', {success:false, message:' Name already used. '      }); }    }  });}

Registers an asynchronous callback function.

<---------------' Nameattempt '------------------name

|

'-------------' Nameresult '---------------> {success:true| | False, Message: ' Name ' | | ' Why Fail '}

Unlike the previous callback function, this callback function requires a server global variable and modifies it.

In the same vein, the latter two arguments are quoted, and they are no different. (Is it impossible to access it without passing it?) )

function handleroomjoining (socket) {  Socket.on(function() {    Socket.leave (currentroom[ Socket.id]);    Joinroom (socket, room.newroom);  });

Registers an asynchronous callback function.

<---------------' Join '------------------

|

Socket out of the original group

|

Joinroom (socket, room.newroom)

This also requires a server global variable, which does not have a parameter.

function handleclientdisconnection (socket) {  Socket.on(function() {    var Nameindex = nameused.indexof (nicknames[socket.id]);     Delete Nameused[nameindex];     Delete nicknames[socket.id];}  )}

Registers an asynchronous callback function.

<------x-------' disconnect '-------x--------

Cleans up variables related to this user.

Node Chat program Instance 02:chat_server.js

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.