1、配置好web服务器环境(tomcat最低7.0以上,建议8.0)
2、java代码
package com.test.websocket;
import java.io.IOException;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint(value = "/message")
public class WebSocketDemo {
@OnOpen
public void openSocket() { // 打开websocket连接
System.out.println("通讯连接已打开,可以进行通话!");
}
@OnMessage
public void dealSocket(String message, Session session) { //数据处理
System.out.println("处理数据。。。");
try {
session.getBasicRemote().sendText(message); //回应的数据
} catch (IOException e) {
e.printStackTrace();
}
}
@OnClose
public void closeSocket() { //关闭websocket连接
System.out.println("通讯连接已断开。。。");
}
}
3、html页面
<%@ 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 type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/validator/jquery.validate.min.js"></script>
<link type="text/css" rel="stylesheet" href="css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<!-- <script type="text/javascript" src="js/pages/websocket_demoa.js"></script> -->
<script type="text/javascript">
$(function() {
var webSocket = null ;
var url = "ws://localhost:8080/WebSocketProject/message" ; //通讯地址
init() ;
webSocket.onopen = function(e) { //打开websocket连接
$("#contentDiv").append("<p>连接成功。。。</p>") ;
}
webSocket.onclose = function(e) {//关闭websocket连接
$("#contentDiv").append("<p>退出交谈。。。</p>") ;
}
$("#but").on("click",function(){
var info = $("#message").val() ;
webSocket.send(info) ; // 消息发送
$("#contentDiv").append("<p>发送:" + info + "</p>") ;
});
webSocket.onmessage = function(e) { //websocket回应处理
$("#contentDiv").append("<p>回应:" + e.data + "</p>") ;
}
function init() {// 初始化操作,判断浏览器是否支持websocket通讯
if ('WebSocket' in window) {
webSocket = new WebSocket(url) ;
} else {
if ('MozWebSocket' in window) {
webSocket = new MozWebSocket(url) ;
} else {
alert("此浏览器不支持websocket。。。") ;
}
}
}
})
</script>
</head>
<body>
<form action="message" method="post" class="form-group form-horizontal">
<div id="contentDiv" style="width:600px;height:300px;overflow:scroll;">
</div>
<label class="col-md-1 control-label">消息:</label>
<div class="col-md-3">
<input type="text" id="message" name="message" class="form-control">
</div>
<input type="button" id="but" class="btn btn-success" value="发送">
</form>
</body>
</html>
如果要实现一对一,一对多聊,只需要将对话的session用静态的map保存起来,用的时候取出来即可。