socket, serversocket, websocket

1. Socket class

Socket allows an application to read and write data from the network, and two applications on different computers can send and receive byte streams over the connection. When sending a message, you need to know the other party’s ip and port. In java, socket refers to the java.net.Socket class.

In java.net.Socket, you can see that socket has various constructors
write picture description here
Take public Socket(String host, int port) as an example, where host is the name or IP address of the remote machine, and port is the port number. If you connect to a local server, its port number is 8080, which can be written in the following format

new Socket(“localhost”, 8080);

Once an instance of the Socket class is successfully created, it can be used to send and receive byte streams. When sending, call the getOutputStream method to obtain a java.io.OutputStream object. To receive information sent by a remote object, you can call the getInputStream method to return a java. io.InputStream object.

serversocket

Now, implementing a server application requires a different approach. The server needs to be on standby at any time, because we don’t know when the client will send a request. At this time, we need to use ServerSocket, which corresponds to the java.net.ServerSocket class.
ServerSocket is different from Socket. ServerSocket waits for the client’s request. Once a connection request is obtained, a Socket instance is created to communicate with the client.

Recall that Socket is a programming interface for network communication. Socket can communicate between the application layer and all layers below, and it provides a relatively simple way to communicate over the network. In Socket programming, the server needs to create a ServerSocket object to listen to the specified port, and accept the client’s connection request through the accept method. The client needs to create a Socket object and connect to the server through the specified port. Then, both the server and the client can use the getInputStream method and the getOutputStream method of the Socket object to read and write data.

WebSocket

What’s the difference between Can you recall sockets and learn about websockets?

Answer: Serversocket and Websocket are two different communication protocols. Serversocket is a class used to implement server-side Socket programming in Java. It is used to listen to a specified port and accept client connection requests. Through Serversocket, the server can create a Socket object to communicate with the client. [2] While Websocket is a protocol for full-duplex communication between a web browser and a server. It allows the server to actively push data to the client without requiring the client to initiate a request. Websocket uses the HTTP protocol for handshake, and then after the connection is established, it realizes real-time communication through a long connection.

Regarding the memory of Socket, Socket is a communication interface between the application layer and all the layers below, which can help us communicate over the network in a relatively simple way. Socket can be used to realize the communication between the client and the server, through which a connection can be established, data can be sent and received. In Socket programming, the server needs to create a ServerSocket object to listen to the specified port and accept the client’s connection request, while the client needs to create a Socket object to connect to the server. Data can be read and written through the input stream and output stream of the Socket object.

To sum up, Serversocket is a class used to implement server-side Socket programming, which is used to listen to a specified port and accept connection requests from clients, while Websocket is a protocol for full-duplex communication between a Web browser and a server. Socket is a communication interface for communication between client and server.

Let’s take a look at webSocket, spring integration implementation, similar to springMVC

 <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-websocket</artifactId>
   <version>${spring.version}</version>
</dependency>
<dependency>
    <groupId>javax.websocket</groupId>
    <artifactId>javax.websocket-api</artifactId>
    <version>1.0</version>
    <scope>provided</scope>
</dependency>

. Implement WebSocketHandler for processing information

package com.fp.controller.websocket;

import java.util.ArrayList;
import java.util.List;

import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

public class MyWebSocketHandler implements WebSocketHandler{
    private List<WebSocketSession> sessions = new ArrayList<WebSocketSession>();

    //Establish
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("afterConnectionEstablished");
        sessions. add(session);

    }
    //Send a message
    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        System.out.println("handleMessage");
        for(WebSocketSession se : sessions){
            se. sendMessage(message);
        }
        System.out.println(message);
        session. sendMessage(message);

    }
    //abnormal
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.out.println("handleTransportError");

    }
    //closure
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        System.out.println("afterConnectionClosed");

    }

    @Override
    public boolean supports PartialMessages() {
        System.out.println("supportsPartialMessages");
        return false;
    }

}

Implement the interceptor HttpSessionHandshakeInterceptor

package com.fp.controller.websocket;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpMessage;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;


public class MyHttpSessionHandshakeInterceptor extends HttpSessionHandshakeInterceptor{
    @Override
    public boolean beforeHandshake(ServerHttpRequest request,
            ServerHttpResponse response, WebSocketHandler wsHandler,
            Map<String, Object> attributes) throws Exception {

        // Solve the problem that The extension [x-webkit-deflate-frame] is not supported
        if (request. getHeaders(). containsKey("Sec-WebSocket-Extensions")) {
            request.getHeaders().set("Sec-WebSocket-Extensions",
                    "permessage-deflate");
        }

        System.out.println("Before Handshake");
       /* String domain = request. getHeaders(). getOrigin();
        System.out.println(domain);
        HttpHeaders headers = response. getHeaders();
        headers.setAccessControlAllowOrigin(domain);
        List<HttpMethod> list = new ArrayList<HttpMethod>();
        list.add(HttpMethod.GET);
        list.add(HttpMethod.POST);
        list.add(HttpMethod.DELETE);
        list.add(HttpMethod.POST);
        list.add(HttpMethod.OPTIONS);
        headers.setAccessControlAllowMethods(list);
        headers.setAccessControlAllowCredentials(true);*/
        /*headers
        response.setHeader("Access-Control-Allow-Headers", "Content-Type,Access-Control-Expose-Headers");
        response.setHeader("Access-Control-Expose-Headers", "Content-Type"); */
        return super.beforeHandshake(request, response, wsHandler, attributes);
    }

    @Override
    public void afterHandshake(ServerHttpRequest request,
            ServerHttpResponse response, WebSocketHandler wsHandler,
            Exception ex) {
        System.out.println("After Handshake");
        /*String domain = request.getHeaders().getOrigin();
        HttpHeaders headers = response. getHeaders();
        headers.setAccessControlAllowOrigin(domain);
        List<HttpMethod> list = new ArrayList<HttpMethod>();
        list.add(HttpMethod.GET);
        list.add(HttpMethod.POST);
        list.add(HttpMethod.DELETE);
        list.add(HttpMethod.POST);
        list.add(HttpMethod.OPTIONS);
        headers.setAccessControlAllowMethods(list);
        headers.setAccessControlAllowCredentials(true);*/
        ex. printStackTrace();
        super.afterHandshake(request, response, wsHandler, ex);
    }
}

spring configuration

<bean id="websocket" class="com.fp.controller.websocket.MyWebSocketHandler"/>

    <websocket:handlers allowed-origins="*">
     <!-- path represents the corresponding connection -->
    <websocket:mapping path="/websocket" handler="websocket"/>
    <!-- This class is the connection flow control method, this method of rewriting HttpSessionHandshakeInterceptor -->
    <websocket:handshake-interceptors>
    <bean class="com.fp.controller.websocket.MyHttpSessionHandshakeInterceptor"/>
    </websocket:handshake-interceptors>
</websocket:handlers>

front page

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <!--<script src="http://libs.baidu.com/jquery/1.10.0/jquery.min.js"></script>-->
        <script src="js/jquery-1.7.2.min.js" type="text/javascript" charset="utf-8"></script>
        <title></title>
    </head>
    <body>
        <input type="" name="" id="sendtext" value="" />
        <input type="button" id="send" value="send" />
        <div id="return">

        </div>
    </body>

    <script type="text/javascript">
        var url = 'ws://localhost:8080/ws/websocket';
        //var url = 'ws://echo.websocket.org/';
        var socket = new WebSocket(url);
            socket.onopen = function( ){
                console.log("open");
                $("#return").text("open");
            }

            socket.onclose = function( ){
                console. log("close ");
                $("#return").text("close");
            }
            socket.onmessage = function(e){
                console.log("onmessage ");
                console.log(e.data);
                $("#return").text(e.data);
            }
            $("#send").click(function(){
                var text = $("#sendtext").val();
                socket. send(text);
            });

    </script>
</html>
websocket principle

It is an application layer protocol. It refers to a set of communication protocols implemented by browsers at present, which are used to solve the situation where the previous HTTP and request response model are not suitable.

First of all, HTTP has the theory of 1.1 and 1.0, which is the so-called keep-alive, which combines multiple HTTP requests into one, but Websocket is actually a new protocol, which has basically nothing to do with the HTTP protocol, just to be compatible with the handshake of existing browsers It is just a specification, that is to say, it is a supplement to the HTTP protocol, which can be understood through such a picture

1) The life cycle of HTTP is defined by Request, that is, one Request and one Response, then in HTTP1.0, this HTTP request is over.
Improvements have been made in HTTP1.1, so that there is a keep-alive, that is, in one HTTP connection, multiple Requests can be sent and multiple Responses can be received.
But please remember that Request = Response is always like this in HTTP, which means that a request can only have one response. And this response is also passive and cannot be initiated actively.
First of all, Websocket is based on the HTTP protocol, or it borrows the HTTP protocol to complete part of the handshake.
It is the same during the handshake phase

First, let’s look at a typical Websocket handshake

GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
Origin: http://example.com