Create a gist now

Instantly share code, notes, and snippets.

Embed
How to use WebSocket of Tomcat
<!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>
<?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>
//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{
}
}
}
@saswatanand

This comment has been minimized.

Show comment
Hide comment
@saswatanand

saswatanand Apr 1, 2013

Thanks! The code snippet was useful to me.

Thanks! The code snippet was useful to me.

@thomasrossetto

This comment has been minimized.

Show comment
Hide comment
@thomasrossetto

thomasrossetto Apr 24, 2013

thank you very much !

thank you very much !

@nirajsalot

This comment has been minimized.

Show comment
Hide comment
@nirajsalot

nirajsalot May 16, 2013

Thanks for sharing this

Thanks for sharing this

@rendeddula

This comment has been minimized.

Show comment
Hide comment
@rendeddula

rendeddula Jun 1, 2013

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

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

@sulmansarwar

This comment has been minimized.

Show comment
Hide comment
@sulmansarwar

sulmansarwar Aug 15, 2013

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

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

@sourav301

This comment has been minimized.

Show comment
Hide comment
@sourav301

sourav301 Sep 29, 2013

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?

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?

@robbyn

This comment has been minimized.

Show comment
Hide comment
@robbyn

robbyn Nov 25, 2013

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

robbyn commented Nov 25, 2013

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

@IslamBesto

This comment has been minimized.

Show comment
Hide comment
@IslamBesto

IslamBesto Jan 11, 2014

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

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

@smerz

This comment has been minimized.

Show comment
Hide comment
@smerz

smerz Jan 29, 2014

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

smerz commented Jan 29, 2014

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

@joleye

This comment has been minimized.

Show comment
Hide comment
@joleye

joleye Mar 4, 2014

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

joleye commented Mar 4, 2014

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

@bromokun

This comment has been minimized.

Show comment
Hide comment
@bromokun

bromokun Mar 19, 2014

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.

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.

@chitan

This comment has been minimized.

Show comment
Hide comment
@chitan

chitan Mar 25, 2014

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

Owner

chitan commented Mar 25, 2014

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

@AiRmode

This comment has been minimized.

Show comment
Hide comment
@AiRmode

AiRmode Jun 8, 2014

If anybody need pom.xml example for this project-here it is. I've just done it and test

<groupId>wschat</groupId>
<artifactId>wschat</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>wschat</name>
<url>http://example.com</url>

<dependencies>
    <dependency>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>tomcat-catalina</artifactId>
        <version>7.0.39</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>tomcat-coyote</artifactId>
        <version>7.0.27</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <configuration>
                <webXml>WEB-INF\web.xml</webXml>
            </configuration>
        </plugin>
    </plugins>
</build>

AiRmode commented Jun 8, 2014

If anybody need pom.xml example for this project-here it is. I've just done it and test

<groupId>wschat</groupId>
<artifactId>wschat</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>wschat</name>
<url>http://example.com</url>

<dependencies>
    <dependency>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>tomcat-catalina</artifactId>
        <version>7.0.39</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>tomcat-coyote</artifactId>
        <version>7.0.27</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <configuration>
                <webXml>WEB-INF\web.xml</webXml>
            </configuration>
        </plugin>
    </plugins>
</build>
@chitan

This comment has been minimized.

Show comment
Hide comment
@chitan

chitan Aug 9, 2014

@AiRmode thanks!

Owner

chitan commented Aug 9, 2014

@AiRmode thanks!

@srikanthgt

This comment has been minimized.

Show comment
Hide comment
@srikanthgt

srikanthgt Aug 26, 2014

WebSocket is working fine on tomcat 7 but i could fidn the same jars in tomcat 8 ,please help me out

WebSocket is working fine on tomcat 7 but i could fidn the same jars in tomcat 8 ,please help me out

@mahantheshp

This comment has been minimized.

Show comment
Hide comment
@mahantheshp

mahantheshp Dec 21, 2015

I am getting exception below exception,while staring the server.(D:\novworkspace.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\lexus-drivers-webapp\WEB-INF\lib\tomcat-servlet-api-7.0.27.jar) - jar not loaded. See Servlet Spec 3.0, section 10.7.2. Offending class: javax/servlet/Servlet.class

I am getting exception below exception,while staring the server.(D:\novworkspace.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\lexus-drivers-webapp\WEB-INF\lib\tomcat-servlet-api-7.0.27.jar) - jar not loaded. See Servlet Spec 3.0, section 10.7.2. Offending class: javax/servlet/Servlet.class

@jaygajera

This comment has been minimized.

Show comment
Hide comment
@jaygajera

jaygajera Mar 18, 2016

can i get all the material of wesocket?

can i get all the material of wesocket?

@achyut

This comment has been minimized.

Show comment
Hide comment
@achyut

achyut Mar 28, 2016

Thank a lot!

achyut commented Mar 28, 2016

Thank a lot!

@pavelantushevich

This comment has been minimized.

Show comment
Hide comment
@pavelantushevich

pavelantushevich Mar 11, 2017

Where did you get the package "org.apache.catalina.websocket" from?
Somehow my catalina.jar (from Tomcat 9) don't has it.
And I can't find it somewhere.
Please, give me link of needed lib or official resourse url.

Where did you get the package "org.apache.catalina.websocket" from?
Somehow my catalina.jar (from Tomcat 9) don't has it.
And I can't find it somewhere.
Please, give me link of needed lib or official resourse url.

@CFM880

This comment has been minimized.

Show comment
Hide comment
@CFM880

CFM880 Mar 17, 2017

@pavelantushevich
WebSocketServlet Deprecated.
Replaced by the JSR356 WebSocket 1.1 implementation and will be removed in Tomcat 8.0.x.
WebSocketServlet @doc

CFM880 commented Mar 17, 2017

@pavelantushevich
WebSocketServlet Deprecated.
Replaced by the JSR356 WebSocket 1.1 implementation and will be removed in Tomcat 8.0.x.
WebSocketServlet @doc

@Manasoft404

This comment has been minimized.

Show comment
Hide comment
@Manasoft404

Manasoft404 Mar 20, 2017

Thank a lot! good

Thank a lot! good

@bhargavbhegde7

This comment has been minimized.

Show comment
Hide comment
@bhargavbhegde7

bhargavbhegde7 May 5, 2017

Thanks!

Thanks!

@dornthomas27

This comment has been minimized.

Show comment
Hide comment
@dornthomas27

dornthomas27 Jan 23, 2018

This is a great code thank you. Going to run it on my site.

This is a great code thank you. Going to run it on my site.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment