Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of WebSocket

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces the example analysis of WebSocket, which is very detailed and has certain reference value. Friends who are interested must finish it!

A brief introduction to Socket

Socket, also known as "sockets", applications usually use "sockets" to send requests to the network or reply to network requests. The original meaning of Socket is "hole" or "socket", which is used as the process communication mechanism of UNIX. Socket can realize network communication between applications.

Socket can use the TCP/IP protocol or the UDP protocol.

TCP/IP protocol

TCP/IP protocol is the most widely used protocol at present, and it is the most basic protocol that constitutes Internet Internet protocol. It is composed of TCP and IP protocols.

TCP protocol: a connection-oriented, reliable, byte-stream-based transport layer communication protocol, which is responsible for the reliable transmission of data.

IP protocol: a data-oriented protocol used in message switching networks, which is mainly responsible for giving each network device a network address to ensure that data is transmitted to the correct destination.

UDP protocol

UDP features: connectionless, unreliable, message-based transport layer protocol, the advantage is that you don't have to worry about it after transmission, and the speed is faster than TCP.

II. Introduction to WebSocket and message push

The systems based on the Bax S architecture mostly use HTTP protocol, and the characteristics of HTTP protocol are as follows:

1 stateless protocol

2 used to send request messages and response messages through Internet

3 use port to receive and send messages, default is port 80

The underlying communication is still done using Socket.

The HTTP protocol determines the connection mode between the server and the client, so it is impossible to directly implement message push (F5 is broken). Some solutions in disguise:

Two-way Communication and message push

Polling: the client sends an Ajax request to the server regularly, and the server returns the response information and closes the connection immediately after receiving the request. Pros: it is easy to write back-end programs. Disadvantages: most of the requests are useless, wasting bandwidth and server resources. Example: suitable for small applications.

Long polling: the client sends an Ajax request to the server. After receiving the request, the server hold stops the connection, returns the response information and closes the connection until there is a new message, and the client sends a new request to the server after processing the response information. Advantages: there are no frequent requests in the absence of messages, and the cost is small. Disadvantages: server hold connections will consume resources, the order of returned data is not guaranteed, and it is difficult to manage and maintain. Comet asynchronous ashx, for example: webQQ, Hi web version, Facebook IM.

Persistent connection: embed a hidden iframe in the page and set the src property of the hidden iframe to either a persistent connection request or a xhr request, so that the server can continuously input data to the client. Advantages: messages arrive instantly, no useless requests are sent, and it is relatively easy to manage. Cons: maintaining a long connection on the server increases overhead. Example: Gmail chat

Flash Socket: embed a Flash program JavaScript that uses the Socket class in the page to communicate with the Socket interface of the server by calling the Socket interface provided by the Flash program. JavaScript controls the display of the page after receiving the information sent by the server. Pros: achieve real instant messaging, not pseudo-instant messaging. Disadvantages: the client must install the Flash plug-in; non-HTTP protocol, can not automatically pass through the firewall. Example: online interactive games.

Websocket:

WebSocket is a network technology that HTML5 began to provide for full-duplex communication between browsers and servers. Depending on this technology, we can realize the long connection between the client and the server, and the two-way real-time communication.

Features:

Event driven

Async

Client socket using ws or wss protocol

Can realize the push function in the real sense.

Disadvantages:

A small number of browsers do not support it, and the degree and manner of browser support are different.

III. WebSocket client

Websocket allows you to establish a connection to a remote server through JavaScript, thus enabling two-way communication between the client and the server. There are two methods in websocket:

1. Send () sends data to the remote server

2. Close () closes the websocket link

Websocket also defines several listening functions.

1. Onopen triggers this event when a network connection is established

2. Onerror triggers this event when an error occurs on the network

3. Onclose triggers this event when websocket is closed

4. Onmessage the event triggered when the websocket receives a message from the server is also the most important listening event in the communication. Msg.data

Websocket also defines a readyState property that returns the state in which websocket is located:

1. CONNECTING (0) websocket is trying to establish a connection with the server

2. OPEN (1) websocket has established a connection with the server

3. CLOSING (2) websocket is closing the connection to the server

4. CLOSED (3) websocket has closed the connection to the server

The url of websocket starts with ws. If you need ssl encryption, you can use wss. When we call the constructor of websocket to build a websocket object (new WebSocket (url)), we can communicate instantly.

WebSocket client var socket; if (typeof (WebSocket) = = "undefined") {alert ("your browser does not support WebSocket"); return } $("# btnConnection") .click (function () {/ / implement the WebSocket object, specifying the address of the server to connect to and the port socket = new WebSocket ("ws://192.168.1.2:8888") / / Open event socket.onopen = function () {alert ("Socket is open"); / / socket.send ("this is a message from the client" + location.href + new Date ());} / / get message event socket.onmessage = function (msg) {alert (msg.data);}; / / close event socket.onclose = function () {alert ("Socket is closed");} / / error event socket.onerror = function () {alert ("error occurred");}}) / / send message $("# btnSend") .click (function () {socket.send ("this is a message from the client" + location.href + new Date ());}) / / close $("# btnClose") .click (function () {socket.close ();}); IV. WebSocket server

JSR356 defines the specification of WebSocket, which is implemented in Tomcat7. JSR356's WebSocket specification uses javax.websocket.* 's API, and you can use the @ ServerEndpoint annotation for a plain Java object (POJO) as the endpoint of the WebSocket server.

@ ServerEndpoint ("/ push") public class EchoEndpoint {@ OnOpen public void onOpen (Session session) throws IOException {/ / the following code is omitted.} @ OnMessage public String onMessage (String message) {/ / the following code is omitted.} @ Message (maxMessageSize=6) public void receiveMessage (String s) {/ / the following code is omitted.} @ OnError public void onError (Throwable t) {/ / the following code is omitted.} @ OnClose public void onClose (Session session CloseReason reason) {/ / the following code is omitted.}}

The above simple code establishes a WebSocket server. The annotation annotation endpoint of @ ServerEndpoint ("/ push") means that the WebSocket server is run on the ws:// [server IP or domain name]: [Server port] / project / push access endpoint, and the client browser can initiate a HTTP persistent connection to the WebSocket client API.

Classes that use ServerEndpoint annotations must have a public no-argument constructor, and the @ onMessage annotated Java method is used to receive incoming WebSocket information, either in text format or in binary format.

OnOpen is called when a new connection is established for this endpoint. Parameters provide more details on the other end of the connection. Session indicates that two WebSocket endpoints are talking to the other end of the connection, which can be understood as a concept similar to HTTPSession.

OnClose is called when the connection is terminated. The parameter closeReason encapsulates more details, such as why a WebSocket connection is closed.

For more advanced customizations such as @ Message annotations, the MaxMessageSize attribute can be used to define the maximum message byte limit. In the sample program, if more than 6 bytes of information is received, an error is reported and the connection is closed.

Package action;import javax.websocket.CloseReason;import javax.websocket.OnClose;import javax.websocket.OnError;import javax.websocket.OnMessage;import javax.websocket.OnOpen;import javax.websocket.Session;import javax.websocket.server.PathParam;import javax.websocket.server.ServerEndpoint;//ws://127.0.0.1:8087/Demo1/ws/ Zhang San @ ServerEndpoint ("/ ws/ {user}") public class WSServer {private String currentUser / / execute @ OnOpen public void onOpen (@ PathParam ("user") String user, Session session) {currentUser = user; System.out.println ("Connected..." + session.getId ());} / / execute @ OnMessage public String onMessage (String message, Session session) {System.out.println (currentUser + ":" + message) when you receive a message Return currentUser + ":" + message;} / / execute @ OnClose public void onClose (Session session, CloseReason closeReason) {System.out.println (String.format ("Session% s closed because of% s", session.getId (), closeReason)) when the connection is closed;} / / execute @ OnError public void onError (Throwable t) {t.printStackTrace ();}} when the connection is wrong

The character Zhang San in url is the path parameter of, and the method that responds to the request is automatically mapped.

5. Test run

Summary and message push framework

Socket is widely used in inter-application communication. If you need to be compatible with lower-version browsers, it is recommended to use reverse ajax or long links; if you are pure mobile or do not need to consider non-modern browsers, you can use websocket directly. Flash is not recommended to implement push messages because it relies on plug-ins and does not support well on the mobile side. There are also some packaged plug-ins for reverse ajax, such as "Pushlet"

6.1.Open source Java message push framework Pushlet

Pushlet is an open source Comet framework, Pushlet uses the observer model: the client sends requests and subscribes to events of interest; the server assigns a session ID to each client as a tag, and the event source sends the new events to the subscriber's event queue by multicast.

Source code address: https://github.com/wjw465150/Pushlet

Pushlet is a comet implementation: under the Servlet mechanism, data is pushed (push) directly from the Java object on the server side to (dynamic) HTML pages without the help of any Javaapplet or plug-ins. It enables the server side to update the web page of client periodically, which is contrary to the traditional request/response method. The browser client is a browser compatible with the JavaScript1.4 version or above (such as InternetExplorer, FireFox) and uses the JavaScript/DynamicHTML feature. The underlying implementation uses a servlet to connect to the browser where the JavaScript is located through Http and push the data to the latter.

6.2.Open source DotNet message push framework SignalR

SignalR is a class library under ASP .NET that enables real-time communication in the Web project of ASP .NET. Establish a Socket connection between the Web web page and the server. When WebSockets is available (that is, the browser supports Html5) SignalR uses WebSockets, and when it does not support it, SignalR will use long polling to achieve the same effect.

Official website: http://signalr.net/

Source code: https://github.com/SignalR/SignalR

The above is all the content of this article "sample Analysis of WebSocket". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report