How to remotely access the local WebSocket server from the public network

The local websocket server is exposed to the public network for access [cpolar intranet penetration]

Article directory

    • The local websocket server is exposed to the public network for access [cpolar intranet penetration]
        • 1. Java server demo environment
        • 2. Introduce the netty framework maven coordinates encapsulated in the third package into the pom file
        • 3. Create a server and call it in interface mode to facilitate external calls.
        • 4. Start the service. If the following message appears, it means the startup is successful. The exposed port defaults to 9999.
        • 5. Create a tunnel to map the intranet port
        • 6. View status->Online tunnel, copy the public network address and port number of the created tunnel
        • 7. Taking the go-based socket client as an example, connect to the java socket server through the public network
        • 8. Download the websocket framework through git
        • 9. Create the client. Note: The Host value is the tunnel public address copied above!!
        • 10. Then start the service and connect to the server. The word returned by the server indicates that the connection is successful.
        • 11. The client enters information in the console and presses Enter.
        • 12. The information sent by the client appears on the server
        • 13. Enter the message in the server console and press Enter
        • 14. The client receives the reply message from the server and the connection is successful.
1. Java server demo environment
  • jdk1.8
  • Framework: springboot + maven
  • Tools IDEA
2. Introduce the netty framework maven coordinates encapsulated in the third package into the pom file
<dependency>
   <groupId>io.github.fzdwx</groupId>
   <artifactId>sky-http-springboot-starter</artifactId>
   <version>0.10.6</version>
</dependency>

Note: The springbootweb starter needs to be commented out in the pom file. The web starter starts the tomcat service by default, which will conflict with the netty service.

20221220152746

3. Create a server and call it in interface mode to facilitate external calls
@GetMapping("/getConnect")
public void getConnect(HttpServerRequest request){<!-- -->

    request.upgradeToWebSocket(ws -> {<!-- -->

    ws.mountOpen(h->{<!-- -->

           ws.send("Connection successful, start chatting!");
       });

     ws.mountText(s -> {<!-- -->

         System.out.println(s);

             //The other party replies
             System.out.println("Client reply: " + s);

             //Get the value entered by the console
             Scanner scanner =new Scanner(System.in);

             String next = scanner.next();

             ws.send(next);

     });

    });

}
4. Start the service. The following message appears to indicate successful startup. The exposed port defaults to 9999

20221220152808

5. Create tunnel mapping intranet port

Here we use cpolar intranet penetration to map intranet ports. It supports http/https/tcp protocols, does not limit traffic, does not require public IP addresses, and does not require setting up a router. It is simple to operate.

  • cpolar one-click installation script: (domestic users)
curl -L https://www.cpolar.com/static/downloads/install-release-cpolar.sh | sudo bash
  • Or short link installation method: (Foreign users)
curl -sL https://git.io/cpolar | sudo bash
  • View cpolar version information
cpolar version

If it displays normally, the installation is successful.

  • cpolar performs token authentication

cpolar official website: https://www.cpolar.com/

Enter the cpolar official website, register an account and log in to the backend. Click Verify on the left. You can view the token code, copy and execute the command for authentication.

cpolar authtoken xxxxxxxxxxxxxxxxxx
  • Configure cpolar to start automatically at boot
sudo systemctl enable cpolar
  • Daemon mode, start cpolar
sudo systemctl start cpolar
  • Check the status of the cpolar daemon. If it is active, it is in normal startup status.
sudo systemctl status cpolar

After cpolar is successfully installed, two default tunnels will be configured by default: an ssh tunnel and a website tunnel, which can be deleted or modified by yourself.

Then expose the local service to the public network through cpolar, access http://127.0.0.1:9200 with the browser, log in to the cpolar web ui interface, create a tcp tunnel, pointing to port 9999

20221220152822

Note: The tunnel selects a temporary TCP address and port, which will change within 24 hours. If you need to fix the TCP address, you can upgrade to the professional package to fix the TCP address!

6. View status->Online tunnel, copy the public network address and port number of the created tunnel

20221220152843

At this point, the websocket server has been exposed from localhost to the public network. Then we create a client to test the public network access to the socket server connection.

7. Taking the go-based socket client as an example, connect to the java socket server through the public network
  • go version: 1.19
  • Tools: vscode
8. Download the websocket framework through git
go get github.com/gorilla/websocket

20221220152904

9. Create a client, note: the Host value is the tunnel public address copied above!!
package main

import (
    "fmt"
    "log"
    "net/url"

    "github.com/gorilla/websocket"
)

func main() {<!-- -->

    // Define the address of the server

    u := url.URL{<!-- -->
        Scheme: "ws",
        Host: "3.tcp.vip.cpolar.cn:10793", //The address is the public network address of the replication tunnel
        Path: "/eth/getConnect"} //Server controller mapping address

    //Establish a connection with the server
    c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
    if err != nil {<!-- -->
        log.Fatal("dial:", err)
    }
    defer c.Close()

    // Block the main thread
    down := make(chan byte)

    //Start a thread to read the data sent from the server
    go func() {<!-- -->
        for {<!-- -->
            _, message, _ := c.ReadMessage()
            fmt.Println("Server reply:" + string(message))
        }
    }()

    //Start a thread to input message
    go func() {<!-- -->

        for {<!-- -->
            var input string

            fmt.Scanln(&input)

            c.WriteMessage(websocket.TextMessage, []byte(input))

        }

    }()

    for {<!-- -->
        <-down
    }
}
10. Then start the service and connect to the server. The word returned by the server indicates that the connection is successful

20221220152924

11. The client enters information in the console and presses Enter

20221220152933

12. Information sent by the client appears on the server

20221220152943

13. Enter the message in the server console and press Enter

20221220152951

14. The client receives the reply message from the server and the connection is successful

20221220153000

It should be noted that the public network address generated by using cpolar for free is a random temporary address and will change within 24 hours. If long-term remote connection is required, it is recommended to configure a fixed TCP port address for it. That is, after logging in to the cpolar official website, click Reserve, reserve a fixed TCP port address, and then configure it into the corresponding tunnel.