I need to implement a fairly simple WebSocket server in Java SE. All it needs to do is accept connections and store the respective sessions, then send a message to all connected client whenever a certain event is fired.
I cannot find a single tutorial for how to do this in regular Java SE. All of them require running with Maven, or deploying it as a WAR - which are all out of the question for this project. I need to run this as a Java SE desktop app.
The tutorials I have found show how to implement an endpoint using annotations like @OnOpen
, @OnMessage
, and @OnClose
. However, none of them explain how to actually initialize the server. I also need to be able to specify a different port number for incoming connections.
Am I missing something? I know people have made chat apps using WebSocket, and that really should not require a web application server. I am not using Maven either, and would prefer to keep it that way for simplicity's sake.
By definition websockets like normal sockets are client-server so yes, you need a server.
Creating a Web Socket Server Instancevar server = new WebSocketServer("ws://localhost:8181"); Any valid URL can be used with the specification of a port, which was not used earlier.
A WebSocketContainer is an implementation provided object that provides applications a view on the container running it. The WebSocketContainer container various configuration parameters that control default session and buffer properties of the endpoints it contains.
REST follow stateless protocol whereas WebSocket follows stateful protocol. In stateless protocol your server won't retain any information or context from previous requests each and every request is independent of the others.
https://github.com/TooTallNate/Java-WebSocket is a full WebSockets server and client implementation in Java SE, no enterprise/web app server needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With