[prenatal education] java websocket server starting from 0

The full text is completed on the basis of IDEA compiler.

This article is for java beginners who have not learned all kinds of Java frameworks

Most java WebSockets on CSDN adopt the spring boot framework

This article does not use any framework related to spring, but only uses maven to import the websocket library

Reference source: https://github.com/TooTallNate/Java-WebSocket/tree/master/src/main/example



First, create a java maven project in IDEA

In POM Import the following dependencies into the XML file


Create chatServer Java file

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.Collections;
import org.java_websocket.WebSocket;
import org.java_websocket.drafts.Draft;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

public class ChatServer extends WebSocketServer {

  public ChatServer(int port) throws UnknownHostException {
    super(new InetSocketAddress(port));

  public ChatServer(InetSocketAddress address) {

  public ChatServer(int port, Draft_6455 draft) {
    super(new InetSocketAddress(port), Collections.<Draft>singletonList(draft));

  public void onOpen(WebSocket conn, ClientHandshake handshake) {//Called when the client connects
    conn.send("Welcome to the server!");
    broadcast("new connection: " + handshake.getResourceDescriptor()); //This method sends a message to all clients connected
    conn.getRemoteSocketAddress().getAddress().getHostAddress() + " entered the room!");

  public void onClose(WebSocket conn, int code, String reason, boolean remote) {//Called when the client disconnects
    broadcast(conn + " has left the room!");
    System.out.println(conn + " has left the room!");

  public void onMessage(WebSocket conn, String message) {//Called when a message sent by the client is received
    System.out.println(conn + ": " + message);

  public void onMessage(WebSocket conn, ByteBuffer message) {
    System.out.println(conn + ": " + message);

  public static void main(String[] args) throws InterruptedException, IOException {
    int port = 8887; // The port number used by the server
    try {
      port = Integer.parseInt(args[0]);
    } catch (Exception ex) {
    ChatServer s = new ChatServer(port);
    System.out.println("ChatServer started on port: " + s.getPort());

    BufferedReader sysin = new BufferedReader(new InputStreamReader(System.in));
    while (true) {
      String in = sysin.readLine();
      if (in.equals("exit")) {

  public void onError(WebSocket conn, Exception ex) {
    if (conn != null) {
      // some errors like port binding failed may not be assignable to a specific websocket

  public void onStart() {
    System.out.println("Server started!");


In this way, a java # websocket server is simply created

have access to http://www.websocket-test.com/ Test your own server, or use a simple client (there are many such simple clients in html and java) to test the connection of the server.

For the function you want to implement, you can rewrite the corresponding method.

In addition, let's talk about possible errors (for beginners)

The websocket server can be connected to the local client, but cannot be connected to the external network.

Possible causes:

1.IP address filling error

InetAddress addr = InetAddress.getLocalHost();
      System.out.println("Local HostAddress: 

java's method of obtaining IP address may obtain 192.168 local IP. You need to enter ipconfig in cmd to view the local IP. In addition, Baidu's IP address is unreliable!! Before I get my own IP, Baidu has always been the input IP, you can find your own IP address.

2.IDEA cannot be networked due to firewall

This mistake is really low-level, but it just happened. The server I wrote myself was put on other people's computers, and other people couldn't connect to the server when they died, but this machine could be connected. Later, it was found that he couldn't connect to the external network because of his IDEA firewall setting.

3. Reasons for setting campus network

This depends on the school settings. If the campus network of our school is not the same access point, it can not be connected to each other. The solution is to connect the client and server to the mobile hotspot at the same time.



Keywords: Java Maven websocket

Added by valtido on Sun, 20 Feb 2022 01:44:49 +0200