WebSocket.之.基础入门-后端响应消息
在《WebSocket.之.基础入门-前端发送消息》的代码基础之上,进行添加代码。代码只改动了:TestSocket.java 和 index.jsp 两个文件。
项目结构如下:
TestSocket.java 代码
package com.charles.socket; import java.io.IOException; import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint; @ServerEndpoint(value = "/helloSocket")
public class TestSocket { /***
* 当建立链接时,调用的方法.
* @param session
*/
@OnOpen
public void open(Session session) { System.out.println("开始建立了链接...");
System.out.println("当前session的id是:" + session.getId());
} /***
* 处理消息的方法.
* @param session
*/
@OnMessage
public void message(Session session, String data) { System.out.println("开始处理消息...");
System.out.println("当前session的id是:" + session.getId());
System.out.println("从前端页面传过来的数据是:" + data); String message = "你好,我是后端程序...";
try {
session.getBasicRemote().sendText(message);
} catch (IOException e) {
e.printStackTrace();
} }
}
index.jsp 代码
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Charles-WebSocket</title> <script type="text/javascript"> var websocket = null;
var target = "ws://localhost:8080/websocket/helloSocket"; function buildConnection() { if('WebSocket' in window) {
websocket = new WebSocket(target);
} else if('MozWebSocket' in window) {
websocket = MozWebSocket(target);
} else {
window.alert("浏览器不支持WebSocket");
} // 添加监听消息的方法
websocket.onmessage = function(event) {
console.log(event)
console.log(event.data)
document.getElementById("serverMsg").innerHTML = "<p>后端消息 :"+ event.data +"</p>"
}
} // 往后台服务器发送消息.
function sendMessage() { var sendmsg = document.getElementById("sendMsg").value;
console.log("发送的消息:" + sendmsg); // 发送至后台服务器中.
websocket.send(sendmsg);
} </script>
</head>
<body> <button onclick="buildConnection();">开始建立链接</button>
<hr>
<input id="sendMsg" /> <button onclick="sendMessage();">消息发送</button>
<div id="serverMsg"></div> </body>
</html>
运行项目,由于改动了代码,建议:重新启动Tomcat服务器。
项目启动后,通过浏览器访问页面,地址:http://localhost:8080/websocket
注意:
一定要先点击,开始建立连接按钮,然后输入内容,在点击消息发送...你懂的.
现在看后端日志....
前端能发送消息,后端也能响应,一切OK...
如有问题,欢迎纠正!!!
如有转载,请标明源处:https://www.cnblogs.com/Charles-Yuan/p/9784555.html