Use socket. io and node. js to build a websocket Application

Source: Internet
Author: User


Websocket is a new communication protocol of html5. it implements two-way communication between browsers and servers. In the WebSocket API, the browser and the server only need to perform a handshake, and then a fast channel is formed between the browser and the server. Data can be directly transmitted to each other.
For more information about websocket, see Wikipedia.

Use WebSocket

To use websocket on the client, you need to create a WebSocket object. You can use the open, send, message, and close methods provided to create, send, listen to, and close the connection. For example, the following code:

if ('WebSocket' in window) {
// create websocket instance
var socket = new WebSocket ('ws: // localhost: 8080');  //turn on
socket.onopen = function (event) {
// send
socket.send ('I am the client and I \' m listening! ');
// listen
socket.onmessage = function (event) {
console.log ('Client received a message', event);
};
// turn off listening
socket.onclose = function (event) {
console.log ('Client notified socket has closed', event);
};    // shut down
//socket.close ()
};
} else {
alert ('This browser does not support WebSocket ~');
}

Currently, browsers such as chrome and firefox support websocket, but IE does not. Next, let's briefly talk about the server's support for websocket.

The server supports many websocket languages and has related open-source projects, such as php phpwebsockets: http://code.google.com/p/phpwebsockets/, Java's jwebsocket:http://jwebsocket.org /.
For more information, see this article: Start Using HTML5 WebSockets Today.

Socket. io

Socket. IO is a websocket library, including the client js and the server nodejs. Official Address: http://socket.io

The client uses socket. io

Go to the latest github clone socket. io version, or directly use the socket. io CDN service:

<script src="http://cdn.socket.io/stable/socket.io.js"></script>

You can create a client js code using the socket. io library below:

var socket = io.connect('http://localhost');
socket.on('news', function (data) {
	console.log(data);
	socket.emit('my other event', { my: 'data' });
});

Socket. on is a listener. When you receive the news from the server, run the function. data is the data returned from the request, and socket. emit is the method for sending messages to the server.

Use socket. io and nodejs to build a websocket Server

Socket. io can not only build the websocket service of the client, but also support the websocket of the nodejs server.

Install socket. io in nodejs

Use the node plug-in management package and run the following command to install socket. io successfully.

Npm install socket. io

If there is no npm or windows users can use github to download socket. io and put it into the node_modules folder. For detailed configuration, refer to: nodejs Tutorial: configure the windows directory structure of nodejs.exe.

Establish socket. io service in nodejs

Through the http module of nodejs, you can easily build a websocket server environment, for example, the following code:

// Introduce the required modules: http and socket.io
var http = require ('http'), io = require ('socket.io');
// Create server
var server = http.createServer (function (req, res) {
  // Send HTML headers and message
  res.writeHead (200, {'Content-Type': 'text / html'});
  res.end ('<h1> Hello Socket Lover! </ h1>');
});
// Port 8000
server.listen (8080);
// Create a socket
var socket = io.listen (server);
// Add connection listener
socket.on ('connection', function (client) {
// If the connection is successful, perform the following monitoring
client.on ('message', function (event) {
console.log ('Received message from client!', event);
});
// Disconnect callback
client.on ('disconnect', function () {
console.log ('Server has disconnected');
});
});

Save it as socket.js and execute it from the command line: node socket.js to start the server, now you can access localhost: 8000.

Use express and socket.io
In the previous article, I mentioned the web framework of nodejs: express. The following code can create a socket application based on express and socket.io:

var app = require ('express'). createServer (),
io = require ('socket.io'). listen (app);
app.listen (80);
app.get ('/', function (req, res) {
res.sendfile (__ dirname + '/index.html');
});
io.sockets.on ('connection', function (socket) {
// Send a message to the client
socket.emit ('news', {hello: 'world'});
socket.on ('my other event', function (data) {
console.log (data);
});
// Broadcast information to users other than the current user
socket.broadcast.emit ('user connected');
// broadcast to all clients
io.sockets.emit ('all users');
});
Like the client method, socket.io uses the on method for monitoring and the emit method for sending. Also provides a broadcast function: broadcast

Write at the end
I have been writing articles recently, mainly because I am afraid that I will get messed up after coming back from the 11th holiday, so I sorted out some recent experiences of learning nodejs in a random way. There is too little information about domestic nodejs, and the learning cost is very high.
A chat room based on express + socket.io that I wrote the night before has been put on the Internet, everyone is welcome to download and test.

The next article may write session authentication in express and socket.io. Because the chat room above uses a session to determine whether the user is logged in. In addition, I wrote a nodejs landlord myself, but the logic is quite complicated, so the code is getting worse and worse. When the test logic is written at the end, it starts to be confused. You have to organize it when you have time. Shame. Shame ~

Source: http://www.js8.in/784.html

Related Article

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.