public
Last active

How to use WebSocket of Tomcat

  • Download Gist
WsChatServlet.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
//This sample is how to use websocket of Tomcat.
package wsapp;
 
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.util.ArrayList;
import org.apache.catalina.websocket.MessageInbound;
import org.apache.catalina.websocket.StreamInbound;
import org.apache.catalina.websocket.WebSocketServlet;
import org.apache.catalina.websocket.WsOutbound;
 
public class WsChatServlet extends WebSocketServlet{
private static final long serialVersionUID = 1L;
private static ArrayList<MyMessageInbound> mmiList = new ArrayList<MyMessageInbound>();
 
public StreamInbound createWebSocketInbound(String protocol){
return new MyMessageInbound();
}
 
private class MyMessageInbound extends MessageInbound{
WsOutbound myoutbound;
 
@Override
public void onOpen(WsOutbound outbound){
try {
System.out.println("Open Client.");
this.myoutbound = outbound;
mmiList.add(this);
outbound.writeTextMessage(CharBuffer.wrap("Hello!"));
} catch (IOException e) {
e.printStackTrace();
}
}
 
@Override
public void onClose(int status){
System.out.println("Close Client.");
mmiList.remove(this);
}
 
@Override
public void onTextMessage(CharBuffer cb) throws IOException{
System.out.println("Accept Message : "+ cb);
for(MyMessageInbound mmib: mmiList){
CharBuffer buffer = CharBuffer.wrap(cb);
mmib.myoutbound.writeTextMessage(buffer);
mmib.myoutbound.flush();
}
}
 
@Override
public void onBinaryMessage(ByteBuffer bb) throws IOException{
}
}
}
chat.html
HTML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
<!DOCTYPE html>
<html>
<head>
<meta charset=UTF-8>
<title>Tomcat WebSocket Chat</title>
<script>
var ws = new WebSocket("ws://localhost:8080/TomcatWebSocket/wschat/WsChatServlet");
ws.onopen = function(){
};
ws.onmessage = function(message){
document.getElementById("chatlog").textContent += message.data + "\n";
};
function postToServer(){
ws.send(document.getElementById("msg").value);
document.getElementById("msg").value = "";
}
function closeConnect(){
ws.close();
}
</script>
</head>
<body>
<textarea id="chatlog" readonly></textarea><br/>
<input id="msg" type="text" />
<button type="submit" id="sendButton" onClick="postToServer()">Send!</button>
<button type="submit" id="sendButton" onClick="closeConnect()">End</button>
</body>
</html>
web.xml
XML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
<?xml version="1.0" encoding="UTF-8"?>
 
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 
<servlet>
<servlet-name>WsChatServlet</servlet-name>
<servlet-class>wsapp.WsChatServlet</servlet-class>
</servlet>
 
<servlet-mapping>
<servlet-name>WsChatServlet</servlet-name>
<url-pattern>/wschat/WsChatServlet</url-pattern>
</servlet-mapping>
 
</web-app>

Thanks! The code snippet was useful to me.

thank you very much !

Thanks for sharing this

i am getting some library files missing exceptions. can you send me war file for this project.

can you please provide the maven dependencies for this gist? Thanks.

Thanks Chitan. I was searching for an implementation of websocket and your example helped a lot. It worked perfect on different browsers on a computer. But i dont know way it did not work across different computers. i.e. messages from one computer is not being delivered to other computer.
Where is the problem?

Hi there, I was wondering if the mmiList should be protected against concurrent usage.

I'm using the tomcat version 7.0.39 and it does'nt work for me, it generate this exception :

GRAVE: "Servlet.service()" pour la servlet WsChatServlet a généré une exception
java.lang.ClassCastException: org.apache.coyote.Request cannot be cast to org.apache.coyote.http11.upgrade.UpgradeInbound

This code only works with Tomcat 7. Tomcat 8 the websocket classes appear to have been refactored.

@IslamBesto I'm using the tomcat version 7.0.34,And your mistakes as

I'm using Tomcat 7.0.52 version ... I cannot get the outbound part sending "Hello client" after connected, only when I turn off my tomcat, my client receives "Hello client" ... and I haven't make any changes ... why???
Btw, I changed the protocol to NIO on tomcat server.xml.

If you can use Tomcat 7.0.52, look at here.
https://gist.github.com/chitan/9761824

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.