HTML5 WebSocket (Client) + javaweb (Server) enables simple chat room functions __mysql

Source: Internet
Author: User
Tags button type emit

Introduction: WebSocket is a new function of HTML5 specification, used to solve the problem of two-way communication between browser and background server, using WebSocket technology, the backstage can push the message to the front end at any time, in order to ensure the unity of the front and back platform, in the traditional stateless HTTP protocol, this is "unable to do".

principle: the client is monitored by HTML5 websocket, the client sends a long connection, and the background request blocking realizes the service-side message updating. The server obtains all the request IDs in the current connection and pushes the messages in real time.

first, the final result chart:

Page style with the bootstrap simple to draw a bit

Interested can go here to play http://ouity.com/barrageclient/← hard poke Me W (゚д゚) W

then look at the directory structure of the client:

The client has a total of three files, mainly index.html and index.js,core.js has only written a few tool methods

The following index.js code is the implementation of the client:

Create a connection where the parameter is the server-side link var socket = new WebSocket ("Ws://localhost:8080/init");

$ (function () {//Initialize load Listen method listen ();}) Send a message to the client, where some parameters are defined to set the color font for the message, but for the time being you are not interested in implementing the function emit () {//encodescript method is used to escape the <> tag and prevent script input.
    Method contents in core.js var text = Encodescript ($ ("#msg"). Val ());  var msg = {"Message": Text, "Color": "#CECECE", "Bubblecolor": "#2E2E2E", "FontSize":
    "A", "Fonttype": "Bold"};
    msg = json.stringify (msg);

    Send a message to the server Socket.send (msg);  The message content sent by itself is statically loaded onto the HTML, and the server implementation itself sends the message that it does not push itself $ ("#content"). Append ("<kbd style= ' color: #" + "cecece" + "; float:right; Font-size: "+ 12 +";
    > "+ text +" </kbd><br/> ");

Empty the Message text box $ ("#msg"). Val (""); function Listen () {//Open connection Triggers socket.onopen = function () {$ (' #content '). Append ("<kbd>welcome!</k
    Bd></br> ");
    }; Trigger socket.onmessage = function (evt) {var data = JSON when receiving a message. Parse (Evt.data); $ ("#content"). Append ("<kbd style= ' color: #" + Data.color + "; font-size:" + data.fontsize + "; margin-top:10px; ')
    > "+ data.username + Say:" + data.message + "</kbd></br>");
    }; Socket.onclose = function (evt) {$ (' #content ') is triggered when the connection is closed. Append ("<kbd>" + "close!" + "</kbd></b
    R> "); The Socket.onerror = function (evt) {$ ("#content") is triggered when a connection error occurs. Append ("<kbd>" + "error!" + "</kbd>
    </br> "); The Send message method Document.onkeydown = function (event) {var e = Event | | window.event | | arguments.callee.caller.ar
    Guments[0];
    if (e && e.keycode = =) {//Enter key emit ();  }
};

Next is the implementation of page index.html:

<! DOCTYPE html>  

the Encodescript method in Core.js

function Encodescript (data) {
    if (null = = Data | | "" = = data {return
        "";
    }
    Return Data.replace ("<", "&lt;"). Replace (">", "&gt;");

server-side directory structure

The service side uses the TOMCAT-WEBSOCKET-API jar package implementation, mainly is the client package below Barrageclient class, all can understand, on two or three lines of code, the other class mainly is expands, interested can write oneself a robust system

Write tired of direct address (defy me ah ╰ (°▽°) ╯)

Client-side code to go straight.

The service-side code is straight off.

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.