Skip to content

Instantly share code, notes, and snippets.

@xtea
Last active April 12, 2019 15:21
Show Gist options
  • Save xtea/25dc4d68b0dba702ee2b to your computer and use it in GitHub Desktop.
Save xtea/25dc4d68b0dba702ee2b to your computer and use it in GitHub Desktop.
websocket demo base on tomcat 8
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.pfl.samples</groupId>
<artifactId>jee7-websocket-configurator</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>jee7-websocket-configurer Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<finalName>jee7-websocket-configurator</finalName>
</build>
</project>
/**
* ChatServerEndPoint.java
* http://programmingforliving.com
*/
package com.pfl.samples.jee7.websocket;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
/**
* ChatServer
* @author Jiji_Sasidharan
*/
@ServerEndpoint(value="/chat", configurator=ChatServerEndPointConfigurator.class)
public class ChatServerEndPoint {
private Set<Session> userSessions = Collections.synchronizedSet(new HashSet<Session>());
/**
* Callback hook for Connection open events. This method will be invoked when a
* client requests for a WebSocket connection.
* @param userSession the userSession which is opened.
*/
@OnOpen
public void onOpen(Session userSession) {
userSessions.add(userSession);
}
/**
* Callback hook for Connection close events. This method will be invoked when a
* client closes a WebSocket connection.
* @param userSession the userSession which is opened.
*/
@OnClose
public void onClose(Session userSession) {
userSessions.remove(userSession);
}
/**
* Callback hook for Message Events. This method will be invoked when a client
* send a message.
* @param message The text message
* @param userSession The session of the client
*/
@OnMessage
public void onMessage(String message, Session userSession) {
System.out.println("Message Received: " + message);
for (Session session : userSessions) {
System.out.println("Sending to " + session.getId());
session.getAsyncRemote().sendText(message);
}
}
}
/**
* ChatServerEndPointConfigurator.java
* http://programmingforliving.com
*/
package com.pfl.samples.jee7.websocket;
import javax.websocket.server.ServerEndpointConfig.Configurator;
/**
* ChatServerEndPointConfigurator
* @author Jiji_Sasidharan
*/
public class ChatServerEndPointConfigurator extends Configurator {
private ChatServerEndPoint chatServer = new ChatServerEndPoint();
@Override
public <T> T getEndpointInstance(Class<T> endpointClass)
throws InstantiationException {
return (T)chatServer;
}
}
<!DOCTYPE html>
<html>
<head>
<title>Chat Room</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" href="resources/styles.css" type="text/css"/>
<script src="resources/chat.js"></script>
</head>
<body onload="connect();" onunload="disconnect();">
<h1> Chat Room </h1>
<textarea id="messages" class="panel message-area" readonly ></textarea>
<div class="panel input-area">
<input id="userName" class="text-field" type="text" placeholder="Name"/>
<input id="messageInput" class="text-field" type="text" placeholder="Message"
onkeydown="if (event.keyCode == 13) sendMessage();" />
<input class="button" type="submit" value="Send" onclick="sendMessage();" />
</div>
</body>
</html>
// Websocket Endpoint url
var host = window.location.host;
var path = window.location.pathname;
var webCtx = path.substring(0, path.indexOf('/', 1));
var endPointURL = "ws://" + window.location.host + webCtx + "/chat";
var chatClient = null;
function connect () {
chatClient = new WebSocket(endPointURL);
chatClient.onmessage = function (event) {
var messagesArea = document.getElementById("messages");
var jsonObj = JSON.parse(event.data);
var message = jsonObj.user + ": " + jsonObj.message + "\r\n";
messagesArea.value = messagesArea.value + message;
messagesArea.scrollTop = messagesArea.scrollHeight;
};
}
function disconnect () {
chatClient.close();
}
function sendMessage() {
var user = document.getElementById("userName").value.trim();
if (user === "")
alert ("Please enter your name!");
var inputElement = document.getElementById("messageInput");
var message = inputElement.value.trim();
if (message !== "") {
var jsonObj = {"user" : user, "message" : message};
chatClient.send(JSON.stringify(jsonObj));
inputElement.value = "";
}
inputElement.focus();
}
* {
margin: auto;
padding: 0px;
}
html, body {
width:90%;
height:90%;
background: #eeeeda;
}
.panel {
border: 2px solid #0078ae;
border-radius: 5px;
width:100%;
}
.message-area {
height: 70%;
resize: none;
box-sizing: border-box;
}
.input-area {
background: #0078ae;
box-shadow: inset 0 0 10px #00568c;
}
.input-area input {
margin: 0.5em 0em 0.5em 0.5em;
}
.text-field {
border: 1px solid grey;
padding: 0.2em;
box-shadow: 0 0 5px #000000;
}
.button {
border: none;
padding: 5px 5px;
border-radius: 5px;
width: 60px;
background: orange;
box-shadow: inset 0 0 10px #000000;
font-weight: bold;
}
.button:hover {
background: yellow;
}
h1 {
font-size: 1.5em;
padding: 5px;
margin: 5px;
}
#userName {
width: 20%;
}
#messageInput {
min-width: 60%;
max-width: 80%;
}
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
</web-app>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment