WebSocketServer.java
package main.java;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.websocket.CloseReason;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
//With this, WebSocket Server
//URL can be wildcarded
@ServerEndpoint("/WebSocketServer")
public class WebSocketServer {
//Session(communication)Map for saving
private static Map<String, Session> session = new HashMap<>();
//Variable to store your ID
String myId = "";
//Variable to store your name
String myName = "";
/**
*Method called when connecting
*/
@OnOpen
public void onOpen(final Session client, final EndpointConfig config) {
/*Processing when establishing a session*/
String log = client.getId() + " Was connected.";
System.out.println(log);
}
/**
*Method called on error
*/
@OnError
public void onError(final Session client, final Throwable error) {
/*Processing when an error occurs*/
String log = client.getId() + " was error. [" + error.getMessage() + "]";
System.out.println(log);
}
/**
*Method called when disconnecting
*/
@OnClose
public void onClose(final Session client, final CloseReason reason) throws IOException {
/*Processing at session release*/
String log = client.getId() + " was closed by " + reason.getCloseCode() + "[" + reason.getCloseCode().getCode()
+ "]";
System.out.println(log);
}
/**
*Method called when the message is called
*/
@OnMessage
public void onMessage(final String text, final Session client) throws IOException {
/*Processing when receiving a message*/
System.out.println("WebSocket reception:" + text);
//It is assumed that the content of the message is operated by separating line breaks and the id is described.
String[] t = text.split("\n");
String event = t[0];
String id = t[1];
System.out.println("EVENT:" + event);
System.out.println("ID:" + id);
switch (event) {
case "login":
//Save Session in HashMap
session.put(id, client);
//Store the ID in a variable.
myId = id;
//Cut out the name
int strSize = id.length();
int cutLength = 4;
int nameCut = strSize - cutLength;
//Save only name in variable
myName = id.substring(0,nameCut);
System.out.println("Cut out name:" + myName);
//Send a string to the session saved by id
Session mySession = session.get(id);
mySession.getBasicRemote().sendText("Welcom to " + myName + " !!");
System.out.println("login:" + id);
break;
case "commit":
//broadcast
for (Session s : session.values()) {
s.getBasicRemote().sendText(myName + ": " + t[1]);
}
System.out.println("commit:" + t[1]);
break;
case "close":
//Removed from session list
System.out.println("ID to delete:" + myId);
//Delete saved session
session.remove(myId);
System.out.println("close:Delete session");
break;
}
}
}
script.js
$(function() {
var url = 'ws://' + window.location.host + '/SampleServer/WebSocketServer';
var ws = null;
var inputId;
console.log('Location:' + window.location.host);
//Variable to generate a 4-digit random number
var min = 1000;
var max = 9999;
//Salt code for attaching to a name and converting it to an ID
var saltCode;
//Press the initButton and it will run here
$('#login').on("click",function() {
if (ws == null) {
inputId = $('#box1').find('input').val();
//If the ID is empty, do not register
if(inputId != "") {
//Initialize Websocket
ws = new WebSocket(url);
//Event handler registration
ws.onopen = onOpen;
ws.onmessage = onMessage;
ws.onclose = onClose;
ws.onerror = onError;
console.log("ID:" + inputId);
} else {
alert("Please enter your ID name!!");
}
}
});
//WebSocket open
function onOpen(event) {
$("#log").prepend("<onopen> " + "<br/>");
console.log("WebSocket connection establishment");
//Generate a 4-digit random integer
saltCode = Math.floor(Math.random() * (max + 1 - min)) + min;
//Explicitly cast to a string
String(saltCode);
//Create ID by attaching salt code
inputId = inputId + saltCode;
console.log('ID with salt code:' + inputId);
ws.send("login\n" + inputId);
};
//WebSocket message
function onMessage(receive) {
$("#log").prepend(receive.data + "<br/><br/>");
console.log("Response message:" + receive.data);
};
//WebSocket error
function onError() {
$("#log").prepend("<onerror> " + "<br/>");
console.log("Error handling");
alert("error");
};
//WebSocket close
function onClose() {
$("#log").prepend("<onclose> " + "<br/>");
ws.send("close\ndelete")
ws = null;
console.log("WebSocket disconnection");
};
//window closed(Example:Closed the browser)Set time event
$(window).on("beforeunload",function() {
ws.onclose(); //WebSocket close
});
//Send a message to the server using WebSocket
$('#send').on('click',function() {
var sendMessage = $('#message').val();
console.log("message:" + sendMessage);
if(sendMessage != "") {
ws.send("commit\n" + sendMessage);
$('#message').val("");
} else {
console.log("I will not send it because it is empty");
}
});
});
index.html
<!DOCTYPE html>
<html>
<head>
<title>WebSocket Server Sample</title>
<meta charset="utf-8"/>
<script src="js/lib/jquery-3.4.1.min.js"></script>
</head>
<body>
<div id="box1">
<input type="text" id="id" placeholder="inputID" />
<button id="login">login</button>
</div>
<br/>
<div id="box2">
<input type="text" id="message" placeholder="inputMessage" />
<button id="send">send</button>
</div>
<br/>
<div id="log"></div>
<script src="js/script.js"></script>
</body>
</html>
Log in as another user and send a message.
You will receive a message. !! !!
I can read the message properly.
Using webSocket in this way, we were able to create a simple chat system. It seems that interesting things can be created by linking with a database or building a system. The above is a simple websocket implementation.
Thank you for reading to the end.
Recommended Posts