OkHttp3 implements websocket proxy function

In the project, it is necessary to realize the function of operating the remote machine terminal through the interface. The webservice service is already provided on the host machine. The page uses html5 to connect with the remote machine through websokcet, and finally the terminal command console is displayed on the interface, and the terminal command operation is performed through the interface input.

The final effect is as follows:



 

     The initial implementation is to directly connect the external interface address (websokcet) of the machine through js, but the project requires that the external interface of the machine cannot be exposed to the outside world, and it must support https, so it can only be connected by implementing a websocet proxy. The basic idea is as follows:

 

       The jswebsocket client end of the page is connected to the console websocket server, the console websocket server is connected to the console client end, and the console client end is connected to the websocket server end of the remote machine, so as to realize a websokcet proxy, where the console is the website of the management console, the idea is there, but The process of implementing this websocket proxy function is too tortuous, and it took several days.

      The difficulty is how to realize an effective two-way connection between the console ws client and the machine's ws server, and obtain the data returned by the machine's ws server. I have tried Java socket API (using @ClientEndpoint) and Java-WebSocket  to implement java ws customer service. However, the effect is not satisfactory, the connection is sometimes automatically disconnected, and the data returned by the machine ws server cannot be effectively obtained, so I can only find another way out. Finally, I accidentally found that okhttp3 also supports ws, with Try the mood, use okhttp3 to realize the java ws client, the final effect is great, okhttp is really powerful, okay, let’s not talk nonsense, go directly to the core proxy of the ws proxy function, because the code is on the intranet, you can only use pictures Shows.

  

 1.js ws client implementation:

     The shell terminal is implemented using term.js ( project home page: http://www.open-open.com/lib/view/home/1410080417997 )

     The ws client code is as follows:

    

 

 

 

2.Console ws server implementation:

     Using spring to implement the console ws server, the specific configuration and code are as follows:

     xml placement:

      

 

      Interceptor code:

    

       Processing class code:

       

 

 

 

 

 

3. Console ws client implementation:

    

 



 

 

 

  This is the realization of the whole websokcet proxy function.

  The corresponding okhttp3 version is as follows:



 

     

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326441555&siteId=291194637