WebSocket的介绍和相关协议可以自行百度哈,我这里直接贴代码,实现客户端和服务端的简易通信
前端代码 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>Insert title here</title>
<script src="js/jquery-1.11.3.min.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<input type="text" id="content"><input type="button" value="发送" id="send">
<br>客户端的消息:<textarea rows="10" cols="10" id="clientShow"></textarea><br/>
服务器端的消息:<textarea rows="10" cols="10" id="serverShow"></textarea>
<script type="text/javascript">
$(function (){
});
var wsServer = null;
var ws = null;
wsServer = "ws://" + location.host+"${pageContext.request.contextPath}" + "/testSocket";
ws = new WebSocket(wsServer); //创建WebSocket对象
ws.onopen = function (evt) {
alert("连接已经建立....");
};
ws.onmessage = function(evt) {//获得后台传来的消息时,触发的事件
alert(evt.data);
$("#serverShow").val(evt.data);
};
$("#send").click(function (){
var message = $("#content").val();
if(message == null || message == ""){
alert("不能发空消息!");
return;
}
ws.send("客户端的消息:"+message);
$("#clientShow").val(message);
});
</script>
</body>
</html>
后端服务器代码
package com.ruicai.web;
import java.util.ArrayList;
import java.util.List;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint(value="/testSocket")
public class WebSocket{
private Session session;
private static List<String> ids=new ArrayList<String>();
@OnOpen
public void onOpen(Session session,EndpointConfig config){
this.session=session;
System.out.println("连接打开来自"+session.getId());
}
@OnMessage
public void onMessage(String message){
for (Session openSession : session.getOpenSessions()) {
openSession.getAsyncRemote().sendText(message+"服务器已经收到消息");
}
System.out.println("webSocket接受来自sessionID"+session.getId()+"的信息:"+message);
}
@OnClose
public void onClose(){
System.out.println("连接关闭");
}
}