dahxya
Last Updated: November 21, 2017
·
9.679K
· davidecek87

Implement WebSocket in a Java Servlet

Preface:

This is a simple way to implement the WebSocket in a servlet Java with Tomcat server.

Requirements:

  • Tomcat 7.x
  • Java J2EE (i use version 7...)
  • File exemple: WSTest/ws.java

Code:

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import org.apache.catalina.websocket.MessageInbound;
import org.apache.catalina.websocket.StreamInbound;
import org.apache.catalina.websocket.WebSocketServlet;
import org.apache.catalina.websocket.WsOutbound;

/*
 * @WebServlet indicates the url of this file (ex: localhost:8080/WSTest/ws)
*/
@WebServlet("/ws")
public class ws extends WebSocketServlet{
    private static final long serialVersionUID = 1L;

@Override
public StreamInbound createWebSocketInbound(String arg0, HttpServletRequest arg1) {

    /*
     * arg1.getRemoteAddr() return the ip address (v4 or v6) of the client
     */
    return new WebSocket(arg1.getRemoteAddr());
}

    /*
     * The WebSocket class!!! :D
     * protected* is for testing with JUnit
     */
    protected class WebSocket extends MessageInbound{

    /*
     * Client stream reference.
     */
    private WsOutbound outbound;
    /*
     * Client IP reference.
     */
        private String ip;

    /*
     * Costructor
     * @param ipAddress
     *  Client ip (v4 or v6).
     */
    protected WebSocket(String ipAddress){
        ip = ipAddress;
    }

    /*
     * Message sender.
     * @param m
     *  message to client.
     */
    private void sendMessage(String m){
        try{
            outbound.writeTextMessage(CharBuffer.wrap((m).toCharArray()));
        }
        catch(IOException ioException){
            System.out.println("error opening websocket");
        }
    }

    /*
     * Client open channel.
     * @param o
     *  Client stream reference.
     */
    @Override
    public void onOpen(WsOutbound o){
        this.outbound = o;
        System.out.println("socket opened!");
    }

    /**
     * Client send a char stream to server.
     * @param buffer
     *  Message buffer.
     */
    @Override
    public void onTextMessage(CharBuffer buffer) throws IOException{
    /**
     * What do you do when client send a message to server.
     */
    }

    /**
     * Client send a byte stream to server.
     * @param buffer
     *  Byte buffer.
     */
    @Override
    public void onBinaryMessage(ByteBuffer buffer) throws IOException {
    /**
     * What do you do when client send a byte stream to server.
     */
    }

    } //WebSocket
}//ws
Say Thanks
Respond