JAVA中WebSocket的简单应⽤(基于BS):⽹页聊天聊天室(区分⽤户)websocket的简单应⽤—实现⽹页聊天/聊天室(区分⽤户)
硬件环境:Wind7
开发环境:eclipse+jdk1.7+tomcat9.0+maven
实现了简单的浏览器端根据不同⽤户发送消息显⽰在⽹页上(即简单的聊天室的实现)
下⾯开始:
1.⾸先我们都知道websocket是基于tcp的⼀种新型的⽹络协议,它实现了双⼯程通信(允许浏览器发信息给服务器)
2.最⼤的特点是他是持久化的⽹络通信协议
⾄于和http的优缺点我就不说了,那么直接开始撸代码吧
⾸先是在前端页⾯(jsp的,html是⼀样的)
<%@ page language="java" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<meta>
<title>Java后端WebSocket的Tomcat实现</title>
</head>
<body>
Welcome<br/><input id="text" type="text"/>
<button "send()">发送消息</button>
<hr/>
<button "closeWebSocket()">关闭WebSocket连接</button>
<hr/>
<div id="message"></div>
</body>
<script type="text/javascript" src="js/jquery-3.3.1.js"></script>
<script type="text/javascript">
var websocket = null;
//判断当前浏览器是否⽀持WebSocket
if ('WebSocket' in window) {
websocket = new WebSocket("ws://localhost:8080/testDemo/websocket/1");
}
else {
alert('当前浏览器 Not support websocket')
}
//连接发⽣错误的回调⽅法
setMessageInnerHTML("WebSocket连接发⽣错误");
};
//连接成功建⽴的回调⽅法
console.info("连接打开...")
setMessageInnerHTML("WebSocket连接成功");
}
/
/接收到消息的回调⽅法
console.info(event.data);
setMessageInnerHTML(event.data);
}
//连接关闭的回调⽅法
console.info("连接关闭...")
setMessageInnerHTML("WebSocket连接关闭");
}
//监听窗⼝关闭事件,当窗⼝关闭时,主动去关闭websocket连接,防⽌连接还没断开就关闭窗⼝,server端会抛异常。 beforeunload = function () {
closeWebSocket();
}
//将消息显⽰在⽹页上
function setMessageInnerHTML(innerHTML) {
var message = ElementById("message").innerHTML += innerHTML + '<br/>';
}
//关闭WebSocket连接
function closeWebSocket() {
websocket.close();
}
/
/发送消息
function send() {
var message = ElementById('text').value;
websocket.send('{"id":2,"message":"'+message+'"}');
}
</script>
</html>
那么在后端:
import java.io.IOException;
import urrent.CopyOnWriteArraySet;
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("/websocket/{id}")
public class WebsocketController {
//存放客户端对应的mywebsocket对象
// private static CopyOnWriteArraySet<WebsocketController> websocketControllers = new CopyOnWriteArraySet<WebsocketController>();
private static urrent.ConcurrentHashMap<String,WebsocketController> websocketControllers = new urrent.ConcurrentHashMap <String,WebsocketController>();
private Session session;//会话
private String id; //表⽰每⼀个Session
/**
* 建⽴连接调⽤⽅法
*/
@OnOpen
public void onOnpen(Session session,@PathParam("id") String id) {
System.out.println("建⽴了连接..."+id);
this.session=session;
this.id = id;
// websocketControllers.add(this);//存放到set中
websocketControllers.put(this.id,this);//存放到set中
}
/**
* 连接关闭调⽤的⽅法
*/
@OnClose
public void onClose(){
System.out.println("连接关闭...");
// ve(this); //从set中删除
}
/**
* 收到客户端消息后调⽤的⽅法
* @param message 客户端发送过来的消息
* @param session 可选的参数
*/
@OnMessage
public void onMessage(String message, Session session) {
//消息的格式:{"id":2,"message":"+message+"}
//new JsonParser()
/
/new JSONPObject()
int i1 = message.indexOf(":");
int i2 = message.indexOf(",");
String id=message.substring(i1+1, i2);
int i3 = message.lastIndexOf(":");
int i3 = message.lastIndexOf(":");
//int i4 = message.lastIndexOf(",");
String msg=message.substring(i3);
System.out.println(id+"来⾃客户端的消息:" + message);
System.out.println(id+"---------");
//取得对应的id
WebsocketController item = (id);
try {
item.sendMessage(msg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//发消息
/*for(WebsocketController item: websocketControllers){
try {
item.sendMessage(message);
/
/ AsyncRemote().sendText(message);
} catch (IOException e) {
e.printStackTrace();
continue;
}
}*/
}
简单网页/**
* 发⽣错误时调⽤
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error){
System.out.println("发⽣错误..");
error.printStackTrace();
}
/**
* @param message
* @throws IOException
*/
public void sendMessage(String message) throws IOException{
System.out.println("开始发送消息");
//BasicRemote().sendText(message);
AsyncRemote().sendText(message);
}
}
<project xmlns="/POM/4.0.0"
xmlns:xsi="/2001/XMLSchema-instance"
xsi:schemaLocation="/POM/4.0.0 /maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion>
<groupId>com.accp.springmvc</groupId>
<artifactId>websocket</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>websocket Maven Webapp</name>
<url></url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!--1.志相关依赖 -->
<!--slf4j规范接⼝ -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.12</version>
</dependency>
<!--logback⽇志 -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.1.7</version>
</dependency>
<!--实现slf4j接⼝并整合 -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.7</version>
</dependency>
<!-- jackson json配置 -->
<!-- mvnrepository/artifact/com./jackson-databind --> <dependency>
<groupId>com.</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.6</version>
</dependency>
<!-- mvnrepository/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.0.0.RELEASE</version>
</dependency>
<!-- mvnrepository/artifact/org.springframework/spring-aspects -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.0.0.RELEASE</version>
</dependency>
<!-- mvnrepository/artifact/org.springframework/spring-context-support --> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>5.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
<!-- mvnrepository/artifact/org.springframework/spring-web -->
<dependency>
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论