登录页 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>
</head>
<body>
<form action="chat.jsp" method="post">
<table border="1">
<tr>
<td>用户名:</td><td><input type="text" name="name"/></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="登录"></td>
</tr>
</table>
</form>
</body>
</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="jquery1.9.0.js"></script>
<script type="text/javascript">
var webSocket = null;
var loginName = '<%=request.getParameter("name") %>';//获取登录账号
$(function(){
if(!window.WebSocket){
alert('你的浏览器不支持WebSocket');
}else{
startConnect();
}
});
function startConnect(){
//记住 是ws开关 是ws开关 是ws开关 ws://IP:端口/项目名/Server.java中的@ServerEndpoint的value
var url = "ws://localhost:8081/TestWebSocket/chat/"+loginName;
webSocket = new WebSocket(url);//一个websocket
webSocket.onerror = function(event) {//websocket的连接失败后执行的方法
onError(event)
};
webSocket.onopen = function(event) {//websocket的连接成功后执行的方法
onOpen(event)
};
webSocket.onmessage = function(event) {//websocket的接收消息时执行的方法
onMessage(event)
};
}
function colseConnect(){//关闭连接
webSocket.close();
window.location.href ='./index.jsp';
/* 跳转登录页 我这里就不清空Users.user中对应的对象 ,
你可以用window.location.href请求到后去删除Users.user的相关对象 然后跳转到index.jsp
用servlet3.0接收请求就行
*/
}
function onMessage(event) {
$("#allMsg").append("<p>" + event.data + "</p>");
}
function onOpen(event) {
$("#allMsg").append("<p>已连接至服务器</p>");
}
function onError(event) {
$("#allMsg").append("<p>连接服务器发生错误</p>");
}
function sendMessage(){
if(webSocket.readyState != 1){//断了或其他原因连不上,就得重新连接一下
startConnect();
}
webSocket.send(loginName+":"+$("#msg").val());//向服务器发送消息
$("#msg").val("");//清空输入框
}
</script>
</head>
<body>
<div id="allMsg"></div>
<input type="text" id="msg"/>
<input type="button" value="发送消息" οnclick="sendMessage()"/>
<input type="button" value="关闭websocket" οnclick="colseConnect()"/>
</body>
</html>
Users.java
package com.yin.user;
import java.util.HashMap;
import java.util.Map;
import com.yin.action.Server;
//所有用户
public class Users {
//保存用户
public static Map<String, Server> user = new HashMap<String, Server>();
}
Server.java
package com.yin.action;
import java.io.IOException;
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.yin.user.Users;
@ServerEndpoint(value = "/chat/{loginName}")
public class Server {//自定义一个服务端 名字随便
private Session session;
/**
* 开始连接websocket
*
* @param session
* @param loginName 当前登录账号
*/
@OnOpen
public void open(Session session, @PathParam("loginName") String loginName) {
this.session = session;
Users.user.put(loginName, this);// 保存当前的对象,用于发送或接收消息
}
/**
* 发送消息
* @param message 发送消息
* @throws IOException
*/
@OnMessage
public void message(String message) throws IOException {
// 发送给全部人
for (Server server : Users.user.values()) {
//全部发送消息
server.session.getBasicRemote().sendText(message);
}
/*
如果是一对一发送消息的话 Users.user中只获取发消息和接收消息的对象 不用获取全部
比如:光头强 发给 熊大
Users.user.get("光头强").session.getBasicRemote().sendText(message);
Users.user.get("熊大").session.getBasicRemote().sendText(message);
*/
}
/**
* 关闭
* @param session
*/
@OnClose
public void close(Session session) {
System.out.println("Close");
}
/**
* 出错
* @param t
* @param session
*/
@OnError
public void error(Throwable t, Session session) {
System.out.println(t.getMessage());
System.out.println("Error");
}
}