Node-based websocket applications

Source: Internet
Author: User
Tags emit

Websocket is introduced in HTML. Because the graduation project needs to use the chat room function, we have studied the application of 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 exampleCode:

If ('websocket 'in window) {// create a websocket instance var socket = new websocket ('ws: // localhost: 100'); // open the socket. onopen = function (event) {// send socket. send ('I am the client and I \' m listening! '); // Listen to socket. onmessage = function (event) {console. log ('client received ed a message', event) ;}; // close the listener socket. onclose = function (event) {console. log ('client notified socket has closed ', event) ;}; // close // socket. close () };} else {alert ('The browser does not support websocket ~ ');
}
Socket. io is a javascript framework, including server and client. It uses unified APIs to encapsulate various real-time connections (such as websocket, flash socket, and Ajax long polling ), this makes the backend connection transparent to developers.
Socket. Io uses the detection function to determine whether to establish a websocket connection, Ajax long-polling connection, or flash. Allows you to quickly create real-time applications.Program.
Socket. Io can be downloaded from GitHub. You can include the socket. Io. js file to the page:
 Code: <SCRIPT src = "http://cdn.socket.io/stable/socket.io.js"> </SCRIPT> [/code At this point, socket. Io is valid on this page. It is time to create a socket: [Code]  //  Create a socket. Io instance and establish a connection  VaR Socket = New Io. socket ('localhost' , {Port: 8080 }); Socket. Connect ();  //  Add a connection listener Socket. On ('connect ', Function  () {Console. Log ( 'Client has connected to the server! ');});  //  Add a connection listener Socket. On ('message ', Function  (Data) {console. Log ( 'Received a message from the server! ' , Data );});  //  Add a listener to close the connection Socket. On ('disconnect ', Function  () {Console. Log ( 'The client has disconnected! ' );});  //  Send a message to the server through socket Function  Sendmessagetoserver (Message) {socket. Send (Message );} 
 
Socket. Io simplifies websocket APIs and unifies the APIS returned for shipping. Transmission includes:
Websocket
Flash socket
Ajax long-polling
Ajax multipart streaming
IFRAME
Jsonp polling
You can also set the second option of any socket. Io constructor. The options include:
Port-the port to be connected
Transports-an array containing different transmission types
Transportoptions-objects used for transmitted parameters, with additional attributes
Socket. Io also provides common connections, disconnection, and message events provided by the local websocket API. Socket also provides methods to encapsulate each event type.

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.

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

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

NPM install socket. Io

For how to configure NPM, see the previous article.Article

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

Server:
 VaR HTTP = require ('http' ), Socketio = Require ('socket. Io' );  VaR Server = http. createserver ( Function  (Req, Res) {res. writehead ( 200, {'content-type': 'text/html' }); Console. Log ( 'Listening at: http: // localhost: 808080' );});  //  Add a connection listener Socketio. Listen (server). On ('connection ',Function  (Client ){  //  Listener successful Client. On ('message ', Function  (MSG) {console. Log ( 'Message received ed :' , MSG); client. Send ( 'Message' , MSG) ;}); client. On ( "Disconnect ", Function  () {Console. Log ( "Server has disconnected" );})}); 

Client:

<HTML>  Incoming chat: & Nbsp; <ul id = "incomingchatmessages"> </ul> <br/> <input type = "text" id = "outgoingchatmessage"> </body> <SCRIPT> $ (  Function  (){  VaR Iosocket = Io. Connect (); iosocket. On ( 'Connect ', Function  () {$ ( '# Incomingchatmessages'). append ($ ('<li> connected </LI>' ); Iosocket. On ( 'Message ', Function  (Message) {$ ( '# Incomingchatmessages'). append ($ ('<li> </LI>' ). Text (Message) ;}); iosocket. On ( 'Disconnect ', Function  () {$ ( '# Incomingchatmessages'). append ('<li> disconnected </LI>' ) ;}); $ ( '# Outgoingchatmessage'). keypress ( Function (Event ){  If (Event. Which = 13 ) {Event. preventdefault (); iosocket. Send ($ ( '# Outgoingchatmessage' ). Val (); $ ( '# Incomingchatmessages'). append ($ ('<li> </LI>'). Text ($ ('# outgoingchatmessage' ). Val (); $ ( '# Outgoingchatmessage'). Val ('' );}});}); </SCRIPT> 
Save the server code as socket. js and execute the following command in the command line:Node socket. jsYou can start the server and open two pages in the browser to test.
Note: The code must be in the same directory as npm_module. Otherwise, the socket. Io module cannot be found.
 
 

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.