The Socket. IO instance in node. js, node. jssocket. io

Source: Internet
Author: User
Tags node server

The Socket. IO instance in node. js, node. jssocket. io

1. Introduction

First Socket. IO Official Website: http://socket.io

The official website is very concise, and there is no API documentation. There is only one simple "How to use" for reference. Because Socket. IO is as simple and easy to use as the official website.

So what is Socket. IO? Socket. IO is a WebSocket library that includes the client js and the server nodejs. It aims to build real-time applications that can be used on different browsers and mobile devices. It automatically selects the best way to implement real-time network applications based on the browser's WebSocket, AJAX long polling, Iframe stream, and other methods, which is very convenient and user-friendly, in addition, the supported browsers reach IE5.5 at the lowest, which should meet most of the requirements.

2. installation and deployment

2.1 installation

First, the installation is very simple. In the node. js environment, there is only one sentence:

Copy codeThe Code is as follows:
Npm install socket. io

2.2 build servers with express

Express is a small Node. js Web application framework, which is often used when building HTTP servers. Therefore, it is explained directly using Socket. IO and express as examples.

Copy codeThe Code is as follows:
Var express = require ('express ')
, App = express ()
, Server = require ('http'). createServer (app)
, Io = require ('socket. io '). listen (server );
Server. listen (3001 );

If you do not use express, see socket. io/# how-to-use

3. Basic usage

It can be divided into two sections of code: the server side and the client side, which are very simple.

Server (app. js ):

Copy codeThe Code is as follows:
// Connect the following code:
App. get ('/', function (req, res ){
Res. sendfile (_ dirname + '/index.html ');});

Io. sockets. on ('connection', function (socket ){
Socket. emit ('new', {hello: 'World '});
Socket. on ('other event', function (data ){
Console. log (data );
});
});

First, the io. sockets. on function accepts the string "connection" as the event for the client to initiate a connection. When the connection is successful, the callback function with the socket parameter is called. When we use socket. IO, we basically process user requests in this callback function.

The most critical functions of socket are emit and on. The former submits (sends) an event (the event name is represented by a string), the event name can be customized, and some default event names are also available, next is an object that indicates the content sent to the socket. The latter receives an event (the event name is represented by a string) and then receives the callback function called by the event, data indicates the received data.

In the preceding example, if we send a news event and receive an other event, the client should receive and send the event accordingly. Yes, the client code is the opposite to the server, and it is very similar.

Client (client. js)

Copy codeThe Code is as follows:
<Script src = "/socket. io/socket. io. js"> </script>
<Script>
Var socket = io. connect ('HTTP: // localhost ');
Socket. on ('News', function (data ){
Console. log (data );
Socket. emit ('other event', {my: 'data '});
});
</Script>

There are two points to note: socket. io. the js path needs to be written correctly. This js file is actually placed in the node_modules folder on the server side and will be redirected when requesting this file, therefore, do not be surprised why the file does not exist on the server, but it still works properly. Of course, you can mount the socket on the server. io. the js file is copied to the local machine to make it the js file of the client, so that you do not have to request this js file from the Node server every time to enhance stability. The second point is to use var socket = io. connect ('website address or ip'); to obtain the socket object, and then you can use socket to send and receive events. For event processing, the code above indicates that after a "news" event is received, the data is printed and the "other event" event is sent to the server.

Note: The built-in default event name, for example, "disconnect", indicates that the client is disconnected, and "message" indicates that a message is received. The Custom Event name should not be the same as the default event name built in Socket. IO to avoid unnecessary trouble.

4. Other common APIs

1). broadcast to all clients: socket. broadcast. emit ('broadcast message ');

2). enter a room (very useful! It is equivalent to a namespace that can broadcast to a specific room without affecting clients in other rooms or not in the room): socket. join ('Your room name ');

3). broadcast a message to a room (the sender cannot receive the message): socket. broadcast. to ('Your room name'). emit ('broadcast room message ');

4 ). broadcast messages to a room (including messages received by the sender) (this API is io. sockets): io. sockets. in ('another room name '). emit ('broadcast room message ');

5 ). force WebSocket communication: (client) socket. send ('Hi'), (server) uses socket. on ('message', function (data.

5. Use Socket. IO to build a chat room

Finally, we end this article with a simple example. Using Socket. IO to build a chat room is about 50 lines of code, and the real-time chat effect is also very good. The following code is provided:

Server (socketChat. js)

Copy codeThe Code is as follows:
// A Dictionary of client connections. When a client connects to the server,
// A unique socketId is generated. This dictionary stores socketId ing to user information (nickname, etc.).
Var connectionList = {};

Exports. startChat = function (io ){
Io. sockets. on ('connection', function (socket ){
// Save socketId and user name during Client Connection
Var socketId = socket. id;
ConnectionList [socketId] = {
Socket: socket
};

// The user enters the chat room and broadcasts the user name to other online users.
Socket. on ('join', function (data ){
Socket. broadcast. emit ('broadcast _ join', data );
ConnectionList [socketId]. username = data. username;
});

// The user leaves the chat room and broadcasts the user's departure to other online users.
Socket. on ('disconnect', function (){
If (connectionList [socketId]. username ){
Socket. broadcast. emit ('broadcast _ quit ',{
Username: connectionList [socketId]. username
});
}
Delete connectionList [socketId];
});

// The user speaks and broadcasts the speech content to other online users.
Socket. on ('say', function (data ){
Socket. broadcast. emit ('broadcast _ say ',{
Username: connectionList [socketId]. username,
Text: data. text
});
});
})
};

Client (socketChatClient. js)

Copy codeThe Code is as follows:
Var socket = io. connect ('HTTP: // localhost ');
// After the connection to the server is complete, submit an "add" event and notify others of your username.
Socket. emit ('join ',{
Username: 'username hehe'
});

// Message displayed after receiving the broadcast from the chat room
Socket. on ('broadcast _ join', function (data ){
Console. log (data. username + 'added to the chatting room ');
});

// After receiving the departure broadcast, the message is displayed.
Socket. on ('broadcast _ quit', function (data ){
Console. log (data. username + 'left the chatroom ');
});

// After receiving a message from someone else, the message is displayed
Socket. on ('broadcast _ say', function (data ){
Console. log (data. username + ':' + data. text );
});

// Assume that there is a text box textarea and a send button. btn-send
// Use jQuery to bind events
$ ('. Btn-send'). click (function (e ){
// Obtain text in the text box
Var text = $ ('textea '). val ();
// Submit a say event and the server will broadcast it upon receiving it
Socket. emit ('say ',{
Username: 'username hehe'
Text: text
});
});

This is a simple chat room DEMO. You can expand it as needed. Socket. IO is basically the process of submitting and receiving various events, and the idea is very simple.


Nodejs serves as the server end of websocket, to push messages to the front end of spring MVC Framework in java,

Use node. js to install the WebSocket Library:
Npm install ws and then create the server:
Var WebSocketServer = require ('ws '). server, wss = new WebSocketServer ({port: 8080}); wss. on ('connection', function (ws) {ws. on ('message', function (message) {console. log ('stored ed: % s', message) ;}); ws. send ('something');}); the client uses the HTML5 standard:
Var ws = new WebSocket ("ws: // 127.0.0.1: 8080/"); ws. onopen = function () {alert ("Opened"); ws. send ("I'm client") ;}; ws. onmessage = function (evt) {alert (evt. data) ;}; ws. onclose = function () {alert ("Closed") ;}; ws. onerror = function (err) {alert ("Error:" + err );};

Nodejs socketis relationship

The socket. io in node. js npm depends on node. 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.