English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
1What is WebSocket?
WebSocket is a natural full-duplex, bidirectional, single-socket connection. With WebSocket, your HTTP request becomes a single request to open a WebSocket connection (WebSocket or WebSocket over TLS (Transport Layer Security, originally known as 'SSL')) and reuses the same connection from the client to the server and from the server to the client. WebSocket reduces latency because once the WebSocket connection is established, the server can send messages when they are available. For example, unlike polling, WebSocket sends only one request. The server does not need to wait for a request from the client. Similarly, the client can send messages to the server at any time. Compared to polling, which sends a request at regular intervals regardless of whether there is available message, a single request greatly reduces latency.
2WebSocket API
The WebSocket API allows you to establish full-duplex, two-way communication between the client application and the server-side process through the Web. The WebSocket interface specifies the methods available to the client and the way the client interacts with the network.
3WebSocket Constructor
To establish a WebSocket connection to the server, use the WebSocket interface by instantiating a WebSocket object with a URL representing the endpoint to be connected. The WebSocket protocol defines two URL schemes (URL schemes) - ws and wss, which are used for non-encrypted and encrypted traffic between the client and server, respectively.
Example: var ws = new WebSocket("ws://www.websocket.org");
4
The WebSocket API is purely event-driven. Application code listens for events on the WebSocket object to handle input data and changes in connection status. The WebSocket protocol is also event-driven.
WebSocket object scheduling4different events:
A、open event:
Once the server responds to the WebSocket connection request, the open event is triggered and a connection is established. The callback function corresponding to the open event is called onopen
Example:
ws.onopen = function(e) { console.log("Connection open..."); };
B、message event:
The message event is triggered when a message is received, and the callback function corresponding to this event is onmessage.
Example:
ws.onmessage = function(e) { if(typeof e.data === "string"){ console.log("String message received", e, e.data); } else { console.log("Other message received", e, e.data); } };
C、error event:
The error event is triggered when an unexpected failure occurs in the response. The callback function corresponding to this event is onerror.
Example:
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.
Example:
ws.onclose = function(e) { console.log("Connection closed", e); };
5
The WebSocket object has two methods: send() and close().
A、send() method:
After establishing a full-duplex, two-way connection between the client and server using WebSocket, the send() method can be called when the connection is open. The send() method can be used to send messages from the client to the server. After sending one or more messages, the connection can remain open, or the close() method can be called to terminate the connection.
Example:
ws.send("Hello WebSocket!");
B, close () method:
Using the close() method, you can close the WebSocket connection or terminate the connection attempt. If the connection is already closed, this method does nothing. After calling close(), you cannot send any data on the already closed WebSocket. You can pass two optional parameters to the close() method: code (a numeric status code) and reason (a text string). Passing these parameters can pass information about the reason for the client closing the connection to the server.
Note: The above is a simple introduction to WebSocket. Below, we will use a simple real-time web page chat example to introduce how to use WebSocket
A: First, create a new project named chatroom here, then create a package and a new class to implement the server-side connection. My class is named ChatWebSocketServlet.Java;
The specific project setup is as shown below:
B: Implement the server-side class ChatWebSocketServlet.java 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: A WebSocket implementation class based on streams (with in-stream), the application should extend this class and implement its abstract methods onBinaryData and onTextData. return new ChatMessageInbound(); } class ChatMessageInbound extends MessageInbound { // MessageInbound: A WebSocket implementation class based on messages (with in-message), 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(CharBuffer 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 outbound = map.get(integer); CharBuffer buffer = CharBuffer.wrap(msg); try { outbound.writeTextMessage(buffer); outbound.flush(); } catch (IOException e) { e.printStackTrace(); } } } } }
C: Implement the front-end page index.jsp (for demonstration purposes, it is not beautified and is quite simple) The specific code is as follows:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>websocket聊天室</title> <style type="text/css"> #chat { text-align: left; width: 600px; height: 500px; width: 600px; } #up { text-align: left; width: 100%; height: 400px; border: 1px solid green; OVERFLOW-Y: auto; } #down { text-align: left; height: 100px; width: 100%; } </style> </head> <body> <h2 align="center">基于HTML5的聊天室</h2> <div align="center" style="width: 100%; height: 700px;"> <div id="chat"> <div id="up"></div> <div id="down"> <textarea type="text" style="width: 602px; height: 100%;" id="send"></textarea> </div> </div> <input type="button" value="Connect" onclick="chat(this);"> <input type="button" value="Send" onclick="send(this);" disabled="disabled" id="send_btn" title="[#1#]"> </div> </body> <script type="text/javascript"> var socket; var receive_text = document.getElementById("up"); var send_text = document.getElementById("send"); function addText(msg) { receive_text.innerHTML += "<br/>" + msg; receive_text.scrollTop = receive_text.scrollHeight; } var chat = function(obj) { obj.disabled = "disabled"; socket = new WebSocket('ws://localhost:8080/chatroom/chat'); receive_text.innerHTML += "<font color=green>Connecting to server...</font>"; //Open Socket socket.onopen = function(event) { addText("<font color=green>连接成功!</font>"); document.getElementById("send_btn").disabled = false; send_text.focus(); document.onkeydown = function(event) { if (event.keyCode === 13 && event.ctrlKey) { send(); } } }; socket.onmessage = function(event) { addText(event.data); }; socket.onclose = function(event) { addText("<font color=red>Connection disconnected! </font>"); obj.disabled = ""; }; if (socket == null) { addText("<font color=red>Connection failed! </font>"); } }; var send = function(obj) { if (send_text.value == "") { return; } socket.send(send_text.value); send_text.value = ""; send_text.focus(); } </script> </html>
Now we have a simple real-time chat page, and next we will deploy the project to Tomcat 7.0 server, and start the server to enable chatting
Display results:
1Enter the server address in the address bar:
http://127.0.0.1:8080/chatroom/index.jsp
Click to connect to the server and the results are as follows:
2Open in two different browsers and send messages to each other (I use Google and Firefox here) and the results are as follows:
The above is what the editor has introduced to everyone about HTML5Based on Tomcat 70 implements WebSocket connection and simple real-time chat, hoping it will be helpful to everyone. If you have any questions, please leave a message, and the editor will reply to everyone in time. I also want to express my sincere gratitude to everyone for supporting the Yana Tutorial website!
Statement: The content of this article is from the Internet, the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.)