Skip to content

Instantly share code, notes, and snippets.

@Oifan
Forked from chitan/WsChat.html
Last active September 16, 2016 15:18
Show Gist options
  • Save Oifan/1331747aa285a5147db8 to your computer and use it in GitHub Desktop.
Save Oifan/1331747aa285a5147db8 to your computer and use it in GitHub Desktop.
How to use WebSocket of Tomcat-7.0.52 --> Deploy and visit URL http://localhost:8080/WsChat/WsChat.html?who=Tester123
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>wschat</groupId>
<artifactId>wschat-app</artifactId>
<version>0.1</version>
<packaging>war</packaging>
<name>WsChat</name>
<properties>
<jvm.version>1.6</jvm.version>
<jvm.signature>java16</jvm.signature>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>animal-sniffer-maven-plugin</artifactId>
<version>1.14</version>
<executions>
<execution>
<id>check-java-version</id>
<phase>compile</phase>
<goals>
<goal>check</goal>
</goals>
<configuration>
<signature>
<groupId>org.codehaus.mojo.signature</groupId>
<artifactId>${jvm.signature}</artifactId>
<version>1.0</version>
</signature>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<encoding>UTF-8</encoding>
<source>${jvm.version}</source>
<target>${jvm.version}</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>2.7</version>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
<warName>WsChat</warName>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.1</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
<!DOCTYPE html>
<!-- move this file to: src/main/webapp/WsChat.html -->
<html>
<head>
<meta charset="utf-8">
<title>Tomcat WebSocket Chat</title>
<script type="text/javascript">
function params2Form(){
var hashParams = window.location.search.substr(1).split('&');
for (var i=0; i<hashParams.length; ++i){
var p = hashParams[i].split('=');
document.getElementById(p[0]).value = decodeURIComponent(p[1]);
}
};
var ws = null;
var users = [];
function onload(){
params2Form();
document.getElementById("msg").focus();
var proto = window.location.protocol == "http:" ? "ws://" : "wss://";
ws = new WebSocket(proto + window.location.host + "/WsChat/chat/"
+ document.getElementById("who").value);
ws.onopen = function(){
document.getElementById("msg").onkeydown = function(event) {
if (event.keyCode == 13) {
postToServer(document.getElementById("msg").value);
}
};
};
ws.onmessage = function(message){
if (message.data.substring(0,1) == "‡") {
if (message.data.substring(1,2) == "+") {
userAdd(message.data.substring(2));
} else {
userDel(message.data.substring(2));
}
} else {
document.getElementById("chatlog").textContent += message.data + "\n";
}
};
}
function postToServer(message){
if (message != '') {
ws.send(message);
document.getElementById("msg").value = "";
}
}
function closeConnect(){
document.getElementById("msg").disabled = true;
ws.close();
}
function userListUpdate(){
var list = "";
for (var i=0; i<users.length; ++i) {
list += "<li>" + users[i] + "</li>";
}
document.getElementById("userList").innerHTML = list;
}
function userAdd(user){
users.push(user);
userListUpdate();
}
function userDel(user){
for (var i=0; i<users.length; ++i) {
if (users[i] == user) {
users.splice(i, 1);
userListUpdate();
return;
}
}
}
</script>
<style type="text/css">
body {background-color:#505050; color:yellow;}
h3 {color: lime;}
table td {text-align:left; vertical-align:top;}
table td + td {background:green; color:white; padding-right:1.5em;}
</style>
</head>
<body onload="onload()">
<h3>WsChat</h3>
<table>
<tr>
<td><textarea id="chatlog" cols="90" rows="25" readonly></textarea></td>
<td><ul id="userList"></ul></td>
</tr>
<tr>
<td colspan="2"><b>Sender:</b> <input id="who" size="20" type="text" readonly /></td>
</tr>
<tr>
<td colspan="2">
<b>Text:</b> <input id="msg" size="88" type="text" />&nbsp;
<button type="button" id="endButton" onClick="closeConnect()">End</button>
</td>
</tr>
</table>
</body>
</html>
// move this file to: src/main/java/wsapp/WsChat.java
// This sample is how to use websocket of Tomcat-7.0.52.
// If you use Servlet-3.0 @ServerEndpoint --> web.xml is not required.
package wsapp;
import java.io.IOException;
import java.util.concurrent.ConcurrentLinkedQueue;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint(value = "/chat/{user}")
public class WsChat {
static final String COMMAND_PREFIX = "\u2021";
private static ConcurrentLinkedQueue<Session> sessionList = new ConcurrentLinkedQueue<Session>();
private static ConcurrentLinkedQueue<String> userList = new ConcurrentLinkedQueue<String>();
private volatile String user;
protected void sendToAll(final String text) {
try {
for (final Session session : sessionList) {
//asynchronous communication
session.getBasicRemote().sendText(text);
}
} catch (IOException e) {
}
}
@OnOpen
public void onOpen(@PathParam("user") String user, final Session session) {
this.user = user;
try {
if (user != null) {
userList.add(user);
sendToAll(String.format("%s+%s", COMMAND_PREFIX, user));
}
sessionList.add(session);
//asynchronous communication
session.getBasicRemote().sendText("Hello!");
for (final String usr : userList) {
session.getBasicRemote().sendText(
String.format("%s+%s", COMMAND_PREFIX, usr)
);
}
} catch (IOException e) {
}
}
@OnClose
public void onClose(final Session session) {
sessionList.remove(session);
if (user != null) {
userList.remove(user);
sendToAll(String.format("%s-%s", COMMAND_PREFIX, user));
}
}
@OnMessage
public void onMessage(final String msg) {
sendToAll(String.format("%-15s: %s", user, msg));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment