近来闲来无事,无意间听同事说起过要做个业务提醒的功能,类似于qq一样,这边处理了,别的登陆用户若是登陆着程序可以收到处理信息,网上搜 方法发现还是webscoket最合适;
于是自己便想学学webscoket,学着自己弄了个两个人聊天的小例子,算是最入门和最简单处理了。大家有想学的话可以参考一下。
下面不多说了,我说说我的开发过程吧:
- 首先先建一个javaweb项目,这个我就不多介绍了,就是最最普通的web项目,大家都懂.
- 然后咱们开始写项目:
第一步:创建java webscoket的后台文件
在项目中新建一个java类,普通的就行,类似于这样:
这个java类的内容是:
package com.webscoket;
import java.util.ArrayList;
import java.util.List;
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;
@ServerEndpoint("/test/{sid}")
public class WebSocketTest{
//记录在线人数
private static int onlineCount = 0;
//记录在线人的相关信息
private static List<WebSocketTest> webSocketSet = new ArrayList<WebSocketTest>();
private Session session;
//传个参数,区分一下发消息的每个人;
private String sid=null;
@OnOpen
public void onOpen(Session session,@PathParam(value = "sid") String sid) {
this.session = session;
this.sid=sid;
webSocketSet.add(this); //加入set中
addOnlineCount();
System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
}
@OnClose
public void onClose() {
webSocketSet.remove(this);
subOnlineCount();
System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
}
@OnMessage
public void onMessage(String message) {
System.err.println(this.sid);
if(this.sid.equals("001")) {
WebSocketTest.sendMessageBySid(message, "002");
}else {
WebSocketTest.sendMessageBySid(message, "001");
}
}
@OnError
public void onError(Session session, Throwable error){
System.err.println("发生错误");
error.printStackTrace();
}
public static synchronized void addOnlineCount() {
WebSocketTest.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketTest.onlineCount--;
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static void sendMessage(String message) {
//群发消息
for(WebSocketTest item:webSocketSet) {
try {
item.session.getBasicRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void sendMessageBySid(String message,String sid) {
for(WebSocketTest item:webSocketSet) {
try {
if(item.sid.equals(sid)) {
item.session.getBasicRemote().sendText(message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
注意:创建完项目后需要导入一下tomcat8的包,因为webscoket是基于tomcat实现,版本最好是8以上;
第二步:后台创建完成后,再创建前端jsp
因为要模拟聊天,所以我在项目上新建了两个jsp,分别命名为client.jsp和server.jsp;
client.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="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script>
var websocket = null;
window.onload=function(){
if('WebSocket' in window){
websocket = new WebSocket("ws://localhost:8080/webscoketProject/test/001");
}else{
alert('当前浏览器 Not support websocket')
}
websocket.onopen = function () {
alert("webscoket连接成功!");
}
websocket.onmessage=function(event){
$("#content").append("<div>user2:"+event.data+"</div>");
}
}
function sendText(){
var value=document.getElementById("client").value;
$("#content").append("<div>user1:"+value+"</div>");
websocket.send(value);
}
function leave(){
websocket.close();
}
</script>
</head>
<body>
<input type="text" id="client">
<button onclick="sendText()">发送</button>||<button onclick="leave()">关闭</button>
<div id="content">
</div>
</body>
</html>
server.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="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script>
var websocket = null;
window.onload=function(){
if('WebSocket' in window){
websocket = new WebSocket("ws://localhost:8080/webscoketProject/test/002");
}else{
alert('当前浏览器 Not support websocket')
}
websocket.onopen = function () {
alert("webscoket连接成功!");
}
websocket.onmessage=function(event){
$("#content").append("<div>user1:"+event.data+"</div>");
}
}
function sendText(){
var value=document.getElementById("server").value;
$("#content").append("<div>user2:"+value+"</div>");
websocket.send(value);
}
function leave(){
websocket.close();
}
</script>
</head>
<body>
<input type="text" id="server">
<button onclick="sendText()">发送</button>||<button onclick="leave()">关闭</button>
<div id="content">
</div>
</body>
</html>
到这里关于整个项目的代码开发就可以了;
第三步:运行项目查看效果:
部署到tomcat下启动,然后在浏览器上打开客户端jsp和服务端jsp
两个页面都提示连接成功就可以聊天了
效果:
有兴趣的小伙伴们可以试试,学习一下webscoket