package cn.bdqn.websocket;
import java.util.HashMap;
import java.util.Map;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import com.alibaba.gov.fastjson.JSON;
import com.alibaba.gov.fastjson.JSONObject;
@ServerEndpoint("/websocket/{name}")
public class WebSocketServer {
private String name;
private Session session;
private static Map<String,WebSocketServer> allClients = new HashMap<String, WebSocketServer>();
@OnOpen
public void onOpen(@PathParam("name")String name,Session session){
System.out.println("onOpen进来了~~~,用户名是:"+name);
this.name=name;
this.session=session;
allClients.put(name, this);
}
@OnMessage
public void onMessage(Session session,String message){
System.out.println("我是OnMessage~~~~~~~~~~~~~~~~~~~~~~~");
JSONObject obj = JSON.parseObject(message);
String to=obj.getString("toUser");
String toMessage=obj.getString("toMessage");
WebSocketServer webSocket = allClients.get(to);
if(webSocket!=null){
Session toSession = webSocket.getSession();
if(toSession.isOpen()){
toSession.getAsyncRemote().sendText(this.getName()+"说:"+toMessage);
session.getAsyncRemote().sendText(this.getName()+"说:"+toMessage);
}
}else{
session.getAsyncRemote().sendText("对方不在线~~~~~~");
}
}
@OnError
public void onError(Session session,Throwable e){
}
@OnClose
public void onClose(Session session){
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Session getSession() {
return session;
}
public void setSession(Session session) {
this.session = session;
}
public static Map<String, WebSocketServer> getAllClients() {
return allClients;
}
public static void setAllClients(Map<String, WebSocketServer> allClients) {
WebSocketServer.allClients = allClients;
}
}
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript">
var websocket=null;
function connection(){
var username=document.getElementById("username").value;
//alert(document.location.host);
if("WebSocket" in window){
websocket=new WebSocket("ws://"+document.location.host+"/TestWebSocket/websocket/"+username);
}else{
alert("浏览器不支持WebSocket");
}
websocket.onopen=function(){
document.getElementById("showMessage").innerHTML="连接已建立,可以聊天了~~~<br/>";
};
websocket.onmessage=function(event){
var data = event.data;
//document.getElementById("showMessage").innerHTML=data;
$("#showMessage").append(data+"<br/>");
};
websocket.onerror=function(){
document.getElementById("showMessage").innerHTML="出现异常了";
};
websocket.onclose=function(){
document.getElementById("showMessage").innerHTML="连接关闭了";
};
window.onbeforunload=function(){
if(websocket!=null){
websocket.close();
}
};
}
function sendMessage(){
var toUser=document.getElementById("toUser").value;
var toMessage=document.getElementById("toMessage").value;
if (websocket!=null) {
var message='{"toUser":"'+toUser+'","toMessage":"'+toMessage+'"}';
alert("消息发送成功!");
websocket.send(message);
}
}
</script>
</head>
<body>
<h1>这里是飞机聊天室,Wellcome!!~~~</h1><br>
请输入你的昵称:<input type="text" name="username" id="username"/><button onclick="connection()">建立连接</button><br/><br/><br/><br/>
接收者:<input type="text" name="toUser" id="toUser"/><br/>
发送的消息:<input type="text" id="toMessage"/><br/>
<button onclick="sendMessage()" >发送</button><br/><br/>
<div id="showMessage"></div>
</body>
</html>