HTML5 implementation of WebSocket connectivity based on Tomcat 7.0 and simple real-time chat _javascript techniques

Source: Internet
Author: User
Tags extend http request

1, what is WebSocket?

WebSocket is a natural full-duplex, bidirectional, single socket connection. Using WebSocket, your HTTP request becomes a single request to open a WebSocket connection (WebSocket or WebSocket over TLS (transportlayer Security, Transport layer safety, formerly known as "SSL"). and reuse the same connection from client to server and server to client. WebSocket reduces latency because once a WebSocket connection is established, the server can send messages when they are available. For example, unlike polling, WebSocket only makes one request. The server does not need to wait for requests from the client. Similarly, clients can send messages to the server at any time. A single request greatly reduces latency, rather than polling, regardless of whether there is a message available, sending a request at intervals.

2, WebSocket API

The WebSocket API enables you to establish Full-duplex two-way communication between the client application and the server-side process through the web. The WebSocket interface prescribes the methods that can be used for the client and how the client interacts with the network.

3. WebSocket constructor function

To establish a WebSocket connection to the server, use the WebSocket interface to instantiate a WebSocket object by pointing to a URL that represents the endpoint to which you want to connect. The WebSocket protocol defines two URL schemes (URL scheme)-WS and WSS, which are used to encrypt and encrypt traffic between the client and the server respectively.

instance: var ws = new WebSocket ("ws://www.websocket.org");

4. WebSocket Event

The WebSocket API is purely event-driven. The application code listens for events on the WebSocket object to handle changes to the input data and connection state. The WebSocket protocol is also event-driven.

The WebSocket object dispatches 4 different events:

A, Open event:

Once the server responds to the WebSocket connection request, the Open event triggers and establishes a connection. The callback function corresponding to the Open event is called OnOpen

Instance:

Ws.onopen = function (e) {
console.log ("Connection open ...");

B, messagess events:

The message event is triggered when messages are received, and the callback function corresponding to the event is onmessage.

Instance:

Ws.onmessage = function (e) {
if (typeof e.data = = "string") {
console.log ("string Message Received", E, E.data); c6/>} else {
console.log ("Other message Received", E, E.data);
}
;

C, error events:

The error event is triggered when responding to an unexpected failure. The callback function corresponding to this event is onerror.
Instance:

Ws.onerror = function (e) {
console.log (' websocked error ');
Handererror ();
}

D, Close event:

The close event is triggered when the WebSocket connection is closed. The callback function corresponding to the Close event is onclose.

Instance:

Ws.onclose = function (e) {
console.log ("Connection closed", e);

5, WebSocket method

The WebSocket object has two methods: Send () and close ().

A, Send () method:

With WebSocket, when a full-duplex two-way connection is established between the client and the server, the Send () method can be invoked when the connection is open. Use the Send () method to send a message to the server from the client. After sending one or more messages, you can leave the connection open or call the Close () method to terminate the connection.

Instance:

Ws.send ("Hello websocket!");

B, Close () method:

Using the Close () method, you can turn off the WebSocket connection or terminate the connection attempt. If the connection is closed, the method does nothing. After you call Close (), you cannot send any data on a websocket that is already closed. You can pass two optional arguments to the Close () method: Code (the numeric status code) and reason (a text string). Passing these parameters enables you to pass information to the server about why the customer closed the connection.

Note: The above is a brief introduction to WebSocket, the following will use a simple web chat case to describe how to use WebSocket

A: Create a new project first my name is chatroom, build a package and then create a new class to implement the server-side connection my class name is Chatwebsocketservlet.java;

The concrete project constructs the following diagram:

B: Write server-side implementation class Chatwebsocketservlet.java, the specific code is as follows:

Package com.yc.chat.Servlet;
Import java.io.IOException;
Import Java.nio.ByteBuffer;
Import Java.nio.CharBuffer;
Import Java.text.SimpleDateFormat;
Import Java.util.Date;
Import Java.util.HashMap;
Import Java.util.Map;
Import Java.util.Set;
Import Javax.servlet.annotation.WebServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Org.apache.catalina.websocket.MessageInbound;
Import Org.apache.catalina.websocket.StreamInbound;
Import Org.apache.catalina.websocket.WebSocketServlet;
Import Org.apache.catalina.websocket.WsOutbound; @WebServlet ("/chat") public class Chatwebsocketservlet extends Websocketservlet {private final Map<integer,
wsoutbound> map = new Hashmap<integer, wsoutbound> ();
Private static final long serialversionuid = -1058445282919079067l; @Override protected Streaminbound createwebsocketinbound (String arg0, httpservletrequest request) {//
Streaminbound: Stream based WebSocket implementation class (with inner flow), applications should extend this class and implement its abstract methods Onbinarydata and Ontextdata.
return new Chatmessageinbound ();Class Chatmessageinbound extends Messageinbound {//messageinbound: Message based WebSocket implementation class (in-band messages),
The application should extend this class and implement its abstract methods Onbinarymessage and Ontextmessage.
@Override protected void OnOpen (Wsoutbound outbound) {Map.put (Outbound.hashcode (), outbound); Super.onopen (outbound);} @Override protected void onClose (int status) {Map.Remove (Getwsoutbound (). Hashcode ()); Super.onclose (status); Override protected void Onbinarymessage (Bytebuffer buffer) throws IOException {} @Override protected void Ontextmessage (C
Harbuffer buffer) throws IOException {String msg = buffer.tostring ();
Date date = new Date ();
SimpleDateFormat SDF = new SimpleDateFormat ("HH:mm:ss");
msg = "<font color=green> anonymous user" + Sdf.format (date) + "</font><br/>" + msg;
Broadcast (MSG); private void Broadcast (String msg) {set<integer> Set = Map.keyset (); for (Integer Integer:set) {wsoutbound out
bound = Map.get (integer);
Charbuffer buffer = charbuffer.wrap (msg); try {outbound.writetextmessage (buffer); OutbouNd.flush ();
catch (IOException e) {e.printstacktrace ();}} }
}
}

C: Implementation of the front page index.jsp (to show that the function is not beautified, relatively rudimentary) the specific code is as follows:

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%> <! DOCTYPE html>  

Such a simple real-time chat page is done, then deploy the project to Tomcat 7.0 server, and open the server can be implemented chat

Results show:

1. Enter the server address in the Address bar:

http://127.0.0.1:8080/chatroom/index.jsp

Click Connect server results as follows:

2. Open and send messages to each other in two different browsers (I use Google and Firefox here) as follows:

The above is a small set to introduce HTML5 based on Tomcat 7.0 to achieve websocket connection and realize a simple real-time chat, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.