C # FAQ 3--websocket and message push

Source: Internet
Author: User
Tags dotnet session id server port

Directory

    • First, Socket introduction
    • Second, WebSocket introduction and message push
    • Third, WebSocket client
    • Iv. WebSocket Server Side
    • Five, test run
    • VI. Summary and message push framework
      • 6.1. Open source Java message push framework Pushlet
      • 6.2. Open source dotnet message push frame SIGNALR
    • Seven, code download
      • 7.1, Java implementation of server-side code and client code download
      • 7.2, dotnet Server-side manual connection implementation code download
      • 7.3, dotnet under the use of Superwebsocket three-party library implementation code download

b/s structure of software projects sometimes clients need to get server messages in real time, but the default HTTP protocol only supports the request response mode, which simplifies the Web server, reduces the burden on the server, and speed up the response, because the server does not need to establish a communication link with the client for a long time. But it is not easy to directly complete the real-time message push function, such as chat room, background information prompt, real-time update data and other functions, but through polling, long polling, long connection, Flash socket and HTML5 defined in the WebSocket can complete the function needs.

First, Socket introduction

The socket is also called a socket, and the application usually makes a request to the network through a "socket" or answers a network request. The English meaning of the socket is "hole" or "socket" as a process communication mechanism for UNIX. Sockets enable network communication between applications.

Sockets can use either the TCP/IP protocol or the UDP protocol.

TCP/IP protocol

The TCP/IP protocol is the most widely used protocol, and it is the most basic protocol that constitutes the Internet Protocol, which consists of TCP and IPs:
TCP protocol: A connection-oriented, reliable, byte-stream-based Transport Layer communication Protocol, which is responsible for the reliability transmission of data.

IP protocol: A data-oriented protocol for message exchange networks, which is responsible for giving each network device a network address to ensure data transfer to the correct destination.

UDP protocol

UDP Features: No connection, unreliable, packet-based Transport layer protocol, the advantage is that after sending no tube, faster than TCP.

Second, WebSocket introduction and message push

b/S architecture of the system using the HTTP protocol, the characteristics of the HTTP protocol:

1 Stateless protocol
2 for sending request messages and response messages over the Internet
3 use port to receive and send messages, default to 80 port
The underlying communication is still done using the socket.

The HTTP protocol determines the connection between the server and the client and does not directly implement message push (F5 is bad), some disguised solutions:

Two-way communication and message push

Polling : The client periodically sends an AJAX request to the server, returning the response information and closing the connection as soon as the server receives the request. Pros: It's easier to write back-end programs. Cons: Half 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, the server receives the request and hold the connection until a new message returns the response information and closes the connection, and the client finishes processing the response and sends a new request to the server. Advantages: In the absence of the message is not frequent requests, the cost of small. Cons: Server hold connections consume resources, return data order is not guaranteed, difficult to manage maintenance. Comet asynchronous Ashx, example: WEBQQ, HI Web version, Facebook IM.

Long connection : Embed a hidden iframe in the page, set the SRC attribute of the hidden IFRAME to a request for a long connection, or use a XHR request, and the server can continuously enter data to the client. The advantage: The message arrives immediately, does not send the useless request, the management also is opposite. Disadvantage: The server maintains a long connection that increases overhead. Example: Gmail Chat

Flash Socket: Embed a flash program JavaScript using the socket class within the page to communicate with the server-side socket interface by invoking the socket interface provided by this flash program. JavaScript controls the display of the page after it receives information from the server side. Pros: Realize real instant communication, not pseudo-instant. Disadvantage: The client must have a Flash plugin installed, a non-HTTP protocol, and cannot automatically traverse the firewall. Example: Network interactive game.

Websocket:
WebSocket is a network technology that HTML5 started to provide full duplex communication between the browser and the server. Relying on this technology can realize the long connection between client and server, bidirectional real-time communication.
Characteristics:
Event-driven
Asynchronous
Client socket with WS or WSS protocol

Enables real-world push functionality

Disadvantages:

A small number of browsers do not support the extent of browser support is different from the way.

Third, WebSocket client

WebSocket allows you to establish a connection to a remote server via JavaScript, 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 listener functions.
1. OnOpen triggers this event when a network connection is established
2. onerror triggers this event when a network error occurs
3. OnClose trigger This event when WebSocket is closed
4, OnMessage when the WebSocket received the message from the server to trigger the event, is also the most important communication in a listening event. Msg.data
WebSocket also defines a readystate property that returns the status of WebSocket:
1, connecting (0) WebSocket is trying to establish a connection to the server
2, OPEN (1) WebSocket and the server has established a connection
3, CLOSING (2) WebSocket shutting down the connection to the server
4, CLOSED (3) WebSocket has closed the connection to the server

WebSocket's URL begins with WS, and if you need SSL encryption you can use WSS, and when we call WebSocket's construction method to build a WebSocket object (new WebSocket (URL)), we can do instant communication.

<! DOCTYPE html>Iv. WebSocket Server Side

JSR356 defines the WebSocket specification, which is implemented in TOMCAT7. The JSR356 WebSocket specification uses the javax.websocket.* API to use a common Java object (POJO) as the endpoint of a WebSocket server using @ServerEndpoint annotations.

@ServerEndpoint ("/push") public class Echoendpoint {@OnOpen public void OnOpen (Session session) throws IOException {//below Code omitted ...}  @OnMessage public string OnMessage (String message) {//The following code is omitted ...} @Message (maxmessagesize=6) public void ReceiveMessage ( String s) {//The following code omitted ...}  @OnError public void OnError (Throwable t) {//The following code is omitted ...}  @OnClose public void OnClose (session session, Closereason reason) {//The following code omitted ...}   }

The above concise code establishes a WebSocket server, the annotation annotation endpoint of the @ServerEndpoint ("/push") indicates that the WebSocket server is running on the Ws://[server IP or domain name]:[ The server port]/the access endpoint of the project/push, and the client browser has been able to initiate an HTTP long connection to the WebSocket client API.
A class that uses serverendpoint annotations must have a common parameterless constructor, and the Java method that @onMessage annotations is used to receive incoming websocket information, either in text format or in binary format.
OnOpen is called when a new connection is established at this endpoint. Parameters provide more detail at the other end of the connection. The session indicates that the other end of the two WebSocket endpoint conversation connection can be understood as a concept similar to httpsession.
The onclose is called when the connection is terminated. The parameter Closereason can encapsulate more details, such as why a websocket connection is off.
More advanced customizations such as @message annotations, the MaxMessageSize property can be used to define the maximum message byte limit, and in the example program, if more than 6 bytes of information is received, the 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;        Execution @OnOpen public void OnOpen (@PathParam ("user") String user, session session) {CurrentUser = user) When the connection is opened; System.out.println ("Connected ...    "+ Session.getid ()); }//Receive message when executing @OnMessage public string OnMessage (string message, Session session) {SYSTEM.OUT.PRINTLN (Curre        NtUser + ":" + message);    return CurrentUser + ":" + message; }//When the connection is closed, execute @OnClose public void OnClose (Session session, Closereason Closereason) {System.out.println (St    Ring.format ("Session%s closed because of%s", Session.getid (), Closereason)); }    Connection error when executing @OnError public void OnError (Throwable t) {t.printstacktrace (); }}

The word Fu Zhangsan in the URL is the path parameter, and the method that responds to the request is automatically mapped.

Five, test run

VI. Summary and message push framework

Socket communication between applications is widely used, if you need to be compatible with a lower version of the browser, it is recommended to use reverse Ajax or long link implementation, if the pure mobile or do not need to consider the non-modern browser can be directly used websocket. Flash implementation of the push message method is not recommended, because the dependency plug-in and phone-side support is not good. About reverse Ajax There are also some packaged plug-ins such as "Pushlet"

6.1. Open source Java message push framework Pushlet

Pushlet is an open-source Comet framework that Pushlet uses the Observer model: a client sends a request, subscribes to an event of interest, and the server assigns a session ID to each client as a token, and the event source sends the newly generated event to the subscriber's event queue in a multicast manner.

Source Address: Https://github.com/wjw465150/Pushlet

Pushlet is a comet implementation: Under the servlet mechanism, data is pushed directly from the server-side Java object (push) to the (dynamic) HTML page without the help of any javaapplet or plugins. It allows the server side to periodically update the client's Web pages, contrary to the traditional request/response approach. Browser client is compatible with JavaScript1.4 versions of browsers (such as InternetExplorer, FireFox) and uses the javascript/dynamichtml feature. The underlying implementation uses a servlet to connect to the browser where JavaScript is located, and pushes the data to the latter.

6.2. Open source dotnet message push frame SIGNALR

SIGNALR is an ASP. NET, the class library can be in ASP. NET to implement real-time communication in Web projects. A socket connection is established between the Web page and the server side, and when WebSockets is available (that is, the browser supports HTML5) SIGNALR uses websockets, and when not supported, SIGNALR uses long polling to ensure the same effect.

Official website: http://signalr.net/

Source: Https://github.com/SignalR/SignalR

Vii. code Download 7.1, Java implementation of server-side code and client code download

Click to download server-side code

Click to download the client code

7.2, dotnet Server-side manual connection implementation code download

Click to download dotnet server-side manual connection implementation code

7.3, dotnet under the use of Superwebsocket three-party library implementation code download

Click to download dotnet using superwebsocket three-party library implementation Code

C # FAQ 3--websocket and message push (GO)

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.