How to make Jetty WebSocket in JAVA?
What is WebSocket?
Web socket is a protocol which provides full duplex communication over the TCP protocol. Web socket is a intermediate server which provides bi-directional communication over TCP protocol.
Bi-directional means both sender and receiver can send messages at a time.
Suppose we want to provide chat facility in any system using web socket. Then first of all we have to establish one server which will handle the chat between two user.
Two user will communicate through that server like first user will send message to server then server will send message to the user.
Examples of WebSocket?
First of all download the jar file for Jetty websocket. Then after create a class to create the Server.
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.websocket.server.WebSocketHandler;
import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;
public class WebSocket {
public static void main(String[] args) throws Exception {
Server server = new Server(9999);
WebSocketHandler wsHandler = new WebSocketHandler() {
@Override
public void configure(WebSocketServletFactory factory) {
factory.register(MyWebSocketHandler.class);
}
};
server.setHandler(wsHandler);
server.start();
server.join();
}
}
When you will run the main method of this class then Jetty Server will run on 9999 port.
After that create one handler class that will handles all the events on this server.
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.annotations.*;
import org.eclipse.jetty.websocket.api.annotations.WebSocket;
import java.io.IOException;
@WebSocket
public class MyWebSocketHandler {
private Session session;
@OnWebSocketClose
public void onClose(int statusCode, String reason) {
System.out.println(“Close: statusCode=” + statusCode + “, reason=” + reason);
}
@OnWebSocketError
public void onError(Throwable t) {
System.out.println(“Error: ” + t.getMessage());
}
@OnWebSocketConnect
public void onConnect(Session session) {
this.session = session;
System.out.println(“Connect: ” + session.getRemoteAddress().getAddress());
try {
session.getRemote().sendString(“Hello Webbrowser”);
} catch (IOException e) {
e.printStackTrace();
}
}
@OnWebSocketMessage
public void onMessage(byte[] data, int offset, int length) {
System.out.println(“Binary Message ====> ” + data);
try {
this.session.getRemote().sendString(“Receiving Binary Data==>”+data);
} catch (IOException e) {
e.printStackTrace();
}
}
@OnWebSocketMessage
public void onMessage(String message) {
System.out.println(“String Message ====> ” + message);
try {
this.session.getRemote().sendString(“Receiving String Data==>”+message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
When anybody will send messages on this port then onMessage method will call. And also we can send messages on this port.