To begin with, your code looks identical to Java and JavaScript code. Both work for what they are intended for, but the fact is that you are trying to connect a WebSocket client to a socket server.
As far as I know, these are two different things regarding this answer .
I never tried it your way. However, if I have a network application that uses a socket, then it would be a clean client / server socket, and if it were a web application, I would also use WebSocket on both sides.
So far, so good..
To do this, this answer suggests using any available WebSocket on the server side, and your problem is solved.
I am using WebSocket for Java, and here is an example implementation that I tested with your client code, and it works both on the client side and the server side.
import org.java_websocket.WebSocket; import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.server.WebSocketServer; import java.net.InetSocketAddress; import java.util.HashSet; import java.util.Set; public class WebsocketServer extends WebSocketServer { private static int TCP_PORT = 4444; private Set<WebSocket> conns; public WebsocketServer() { super(new InetSocketAddress(TCP_PORT)); conns = new HashSet<>(); } @Override public void onOpen(WebSocket conn, ClientHandshake handshake) { conns.add(conn); System.out.println("New connection from " + conn.getRemoteSocketAddress().getAddress().getHostAddress()); } @Override public void onClose(WebSocket conn, int code, String reason, boolean remote) { conns.remove(conn); System.out.println("Closed connection to " + conn.getRemoteSocketAddress().getAddress().getHostAddress()); } @Override public void onMessage(WebSocket conn, String message) { System.out.println("Message from client: " + message); for (WebSocket sock : conns) { sock.send(message); } } @Override public void onError(WebSocket conn, Exception ex) {
According to your main method, just:
new WebsocketServer().start();
You may need to manipulate your code to fit this implementation, but this should be part of the job.
Here is the test result with 2 tests:
New connection from 127.0.0.1 Message from client: Ping Closed connection to 127.0.0.1 New connection from 127.0.0.1 Message from client: Ping
Here is the WebSocket maven configuration, otherwise upload the JAR file / s manually and import them into your development / development environment:
<dependency> <groupId>org.java-websocket</groupId> <artifactId>Java-WebSocket</artifactId> <version>1.3.0</version> </dependency>
Link to WebSocket .