Java WebSocket server and client implementation

   I recently received an instruction from the boss to study the fact that WebSocket is a god. After receiving the instruction, I went crazy with Baidu. After four days, I tried the online demo N times, but none of them were successful. I also bought an introductory book, according to the book. The first demo, the final result is that tomcat runs normally, but ws access has been failing. Of course, I finally found the reason. I have to say that the demos on the Internet are actually correct (most of them), but some key points are not explained clearly, otherwise I will not mess around for four days.

   I won't talk about the content of WebSocket. There are a lot of them on the Internet. This article mainly explains that java implements simple webSocket communication. I hope it will help friends who are just starting to learn WebSocket like me! ! !

1. Environment: tomcat8.5.12 + jdk1.8.0_121, in addition need to rely on a jar package: Java-WebSocket-1.3.0.jar, eclipse is best to use 3.6 or above, mine is Version: Luna Release (4.4.0), I heard that WebSocket is only supported in versions 3.6 and above.

2. After preparing the above environment, start to create a new Web project: 1. Java to

write the WebSocket server. In fact, this class is quite simple. It simply tells the client the received message after receiving the client message. The code is as follows:
import javax.websocket.OnMessage;
import javax.websocket.server.ServerEndpoint;


@ServerEndpoint("/websocket/demo")//This is a class annotation that tells the virtual machine that the class is annotated as a WebSocket endpoint
public class MyServer {

	@OnMessage //Here is the method annotation, which is triggered when a message from the client is received
	public String echo(String clientMessage){
		return "Received message from client: " + clientMessage;
	}
}

This is done on the server side.
2. Write the client, here is an html implementation:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>WebSocket Client</title>

<script type="text/javascript" language="javascript">
	was the web socket;
	
	function init()
	{
		output = document.getElementById("output");
	}
	
	function send()
	{
		var wsUri = "ws://localhost:8080/WebSocketDemo1/websocket/demo";
		writeToScreen("Connecting to : "+ wsUri);
		websocket = new WebSocket(wsUri);
		websocket.onopen = function(evt)
		{
			writeToScreen("Connect Success!");
			doSend(document.getElementById("textID").value);
		};
		websocket.onmessage = function (possibly)
		{
			writeToScreen("Received Message: "+ evt.data);
			websocket.close();
		};
		websocket.onerror = function (evt)
		{
			writeToScreen('<span style="color:red;">ERROR:</span>'+evt.data);
		};
	}
	function doSend (message)
	{
		websocket.send(message);
		writeToScreen("Send Message : "+message);
	}
	
	function writeToScreen(message)
	{
		var pre = document.createElement("p");
		pre.style.wordWrap = "break-word";
		pre.innerHTML = message;
		output.appendChild(pre)
	}
	
	window.addEventListener("load", init, false);
	
</script>
</head>
<body>
	<h1>WebSocket Client</h1>
	
	<div style="text-align:left;">
	<form action="">
		<input onclick="send()" value="Send Message" type="button">
		<input id="textID" name="message" value="Hello Web Socket" type="text">
		<br>
	</form>
	
	</div>
	<div id="output"></div>
</body>
</html>

At this point, the client is done.

3. This step is also where the demo I watched online did not describe in detail: Publish the WebSocket server program, copy the project directly to the webapps directory of tomcat, as shown in the figure:



Start the service, and then visit the home page of the project (IE10 or above, Google Browser, you can search which browsers support it):







ps: 1. In the server-side program, the parameters of the annotation class: /websocket/demo, this is the same as the ws address in the jsp page, if the server side writes like this :/demo, then the uri in jsp is: ws://localhost:8080/WebSocketDemo1/demo
2. When publishing the program in tomcat, you must pay attention to the WEB-INF file after clicking the project under webapps folder, I started it because eclipse built the project and put it directly in this directory, but when building the project, the classes file storage directory was not set, and it was unsuccessful.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326781720&siteId=291194637