Skip to content

Commit d1929cc

Browse files
committed
整合websocket实现群聊,点对点聊天
1 parent bf4bf8c commit d1929cc

File tree

9 files changed

+448
-0
lines changed

9 files changed

+448
-0
lines changed

springboot-websocket/.gitignore

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
HELP.md
2+
/target/
3+
!.mvn/wrapper/maven-wrapper.jar
4+
5+
### STS ###
6+
.apt_generated
7+
.classpath
8+
.factorypath
9+
.project
10+
.settings
11+
.springBeans
12+
.sts4-cache
13+
14+
### IntelliJ IDEA ###
15+
.idea
16+
*.iws
17+
*.iml
18+
*.ipr
19+
20+
### NetBeans ###
21+
/nbproject/private/
22+
/nbbuild/
23+
/dist/
24+
/nbdist/
25+
/.nb-gradle/
26+
/build/
27+
28+
### VS Code ###
29+
.vscode/

springboot-websocket/pom.xml

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4+
<modelVersion>4.0.0</modelVersion>
5+
<parent>
6+
<groupId>org.springframework.boot</groupId>
7+
<artifactId>spring-boot-starter-parent</artifactId>
8+
<version>2.1.3.RELEASE</version>
9+
<relativePath/> <!-- lookup parent from repository -->
10+
</parent>
11+
<groupId>cn.tellsea</groupId>
12+
<artifactId>springboot-websocket</artifactId>
13+
<version>0.0.1-SNAPSHOT</version>
14+
<name>springboot-websocket</name>
15+
<description>Demo project for Spring Boot</description>
16+
17+
<properties>
18+
<java.version>1.8</java.version>
19+
</properties>
20+
21+
<dependencies>
22+
<dependency>
23+
<groupId>org.springframework.boot</groupId>
24+
<artifactId>spring-boot-starter-web</artifactId>
25+
</dependency>
26+
<dependency>
27+
<groupId>org.springframework.boot</groupId>
28+
<artifactId>spring-boot-starter-thymeleaf</artifactId>
29+
</dependency>
30+
<!-- https://blog.csdn.net/qq_38455201/article/details/80374712 -->
31+
<dependency>
32+
<groupId>org.springframework.boot</groupId>
33+
<artifactId>spring-boot-starter-websocket</artifactId>
34+
</dependency>
35+
36+
<dependency>
37+
<groupId>org.springframework.boot</groupId>
38+
<artifactId>spring-boot-starter-test</artifactId>
39+
<scope>test</scope>
40+
</dependency>
41+
42+
<dependency>
43+
<groupId>org.projectlombok</groupId>
44+
<artifactId>lombok</artifactId>
45+
</dependency>
46+
47+
<dependency>
48+
<groupId>com.alibaba</groupId>
49+
<artifactId>fastjson</artifactId>
50+
<version>1.2.56</version>
51+
<scope>compile</scope>
52+
</dependency>
53+
</dependencies>
54+
55+
<build>
56+
<plugins>
57+
<plugin>
58+
<groupId>org.springframework.boot</groupId>
59+
<artifactId>spring-boot-maven-plugin</artifactId>
60+
</plugin>
61+
</plugins>
62+
</build>
63+
64+
</project>
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package cn.tellsea;
2+
3+
import org.springframework.boot.SpringApplication;
4+
import org.springframework.boot.autoconfigure.SpringBootApplication;
5+
6+
@SpringBootApplication
7+
public class SpringbootWebsocketApplication {
8+
9+
public static void main(String[] args) {
10+
SpringApplication.run(SpringbootWebsocketApplication.class, args);
11+
}
12+
13+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package cn.tellsea.config;
2+
3+
import org.springframework.context.annotation.Bean;
4+
import org.springframework.context.annotation.Configuration;
5+
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
6+
7+
/**
8+
* websocket的配置
9+
*/
10+
@Configuration
11+
public class WebSocketConfig {
12+
13+
@Bean
14+
public ServerEndpointExporter serverEndpointExporter() {
15+
return new ServerEndpointExporter();
16+
}
17+
}
Lines changed: 160 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,160 @@
1+
package cn.tellsea.socket;
2+
3+
import com.alibaba.fastjson.JSON;
4+
import com.alibaba.fastjson.JSONObject;
5+
import lombok.extern.slf4j.Slf4j;
6+
import org.springframework.stereotype.Component;
7+
8+
import javax.websocket.*;
9+
import javax.websocket.server.PathParam;
10+
import javax.websocket.server.ServerEndpoint;
11+
import java.io.IOException;
12+
import java.util.HashMap;
13+
import java.util.Map;
14+
import java.util.Set;
15+
import java.util.concurrent.ConcurrentHashMap;
16+
17+
@Slf4j
18+
@Component
19+
@ServerEndpoint("/websocket/{username}")
20+
public class WebSocket {
21+
22+
/**
23+
* 在线人数
24+
*/
25+
public static int onlineNumber = 0;
26+
/**
27+
* 以用户的姓名为key,WebSocket为对象保存起来
28+
*/
29+
private static Map<String, WebSocket> clients = new ConcurrentHashMap<String, WebSocket>();
30+
/**
31+
* 会话
32+
*/
33+
private Session session;
34+
/**
35+
* 用户名称
36+
*/
37+
private String username;
38+
39+
/**
40+
* OnOpen 表示有浏览器链接过来的时候被调用
41+
* OnClose 表示浏览器发出关闭请求的时候被调用
42+
* OnMessage 表示浏览器发消息的时候被调用
43+
* OnError 表示有错误发生,比如网络断开了等等
44+
*/
45+
46+
/**
47+
* 建立连接
48+
*
49+
* @param session
50+
*/
51+
@OnOpen
52+
public void onOpen(@PathParam("username") String username, Session session) {
53+
onlineNumber++;
54+
log.info("现在来连接的客户id:" + session.getId() + "用户名:" + username);
55+
this.username = username;
56+
this.session = session;
57+
log.info("有新连接加入! 当前在线人数" + onlineNumber);
58+
try {
59+
//messageType 1代表上线 2代表下线 3代表在线名单 4代表普通消息
60+
//先给所有人发送通知,说我上线了
61+
Map<String, Object> map1 = new HashMap<>();
62+
map1.put("messageType", 1);
63+
map1.put("username", username);
64+
sendMessageAll(JSON.toJSONString(map1), username);
65+
66+
//把自己的信息加入到map当中去
67+
clients.put(username, this);
68+
//给自己发一条消息:告诉自己现在都有谁在线
69+
Map<String, Object> map2 = new HashMap<>();
70+
map2.put("messageType", 3);
71+
//移除掉自己
72+
Set<String> set = clients.keySet();
73+
map2.put("onlineUsers", set);
74+
sendMessageTo(JSON.toJSONString(map2), username);
75+
} catch (IOException e) {
76+
log.info(username + "上线的时候通知所有人发生了错误");
77+
}
78+
79+
80+
}
81+
82+
@OnError
83+
public void onError(Session session, Throwable error) {
84+
log.info("服务端发生了错误" + error.getMessage());
85+
//error.printStackTrace();
86+
}
87+
88+
/**
89+
* 连接关闭
90+
*/
91+
@OnClose
92+
public void onClose() {
93+
onlineNumber--;
94+
//webSockets.remove(this);
95+
clients.remove(username);
96+
try {
97+
//messageType 1代表上线 2代表下线 3代表在线名单 4代表普通消息
98+
Map<String, Object> map1 = new HashMap<>();
99+
map1.put("messageType", 2);
100+
map1.put("onlineUsers", clients.keySet());
101+
map1.put("username", username);
102+
sendMessageAll(JSON.toJSONString(map1), username);
103+
} catch (IOException e) {
104+
log.info(username + "下线的时候通知所有人发生了错误");
105+
}
106+
log.info("有连接关闭! 当前在线人数" + onlineNumber);
107+
}
108+
109+
/**
110+
* 收到客户端的消息
111+
*
112+
* @param message 消息
113+
* @param session 会话
114+
*/
115+
@OnMessage
116+
public void onMessage(String message, Session session) {
117+
try {
118+
log.info("来自客户端消息:" + message + "客户端的id是:" + session.getId());
119+
JSONObject jsonObject = JSON.parseObject(message);
120+
String textMessage = jsonObject.getString("message");
121+
String fromusername = jsonObject.getString("username");
122+
String tousername = jsonObject.getString("to");
123+
//如果不是发给所有,那么就发给某一个人
124+
//messageType 1代表上线 2代表下线 3代表在线名单 4代表普通消息
125+
Map<String, Object> map1 = new HashMap<>();
126+
map1.put("messageType", 4);
127+
map1.put("textMessage", textMessage);
128+
map1.put("fromusername", fromusername);
129+
if (tousername.equals("All")) {
130+
map1.put("tousername", "所有人");
131+
sendMessageAll(JSON.toJSONString(map1), fromusername);
132+
} else {
133+
map1.put("tousername", tousername);
134+
sendMessageTo(JSON.toJSONString(map1), tousername);
135+
}
136+
} catch (Exception e) {
137+
log.info("发生了错误了");
138+
}
139+
}
140+
141+
public void sendMessageTo(String message, String ToUserName) throws IOException {
142+
for (WebSocket item : clients.values()) {
143+
if (item.username.equals(ToUserName)) {
144+
item.session.getAsyncRemote().sendText(message);
145+
break;
146+
}
147+
}
148+
}
149+
150+
public void sendMessageAll(String message, String FromUserName) throws IOException {
151+
for (WebSocket item : clients.values()) {
152+
item.session.getAsyncRemote().sendText(message);
153+
}
154+
}
155+
156+
public static synchronized int getOnlineCount() {
157+
return onlineNumber;
158+
}
159+
160+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package cn.tellsea.web;
2+
3+
import lombok.extern.slf4j.Slf4j;
4+
import org.springframework.stereotype.Controller;
5+
import org.springframework.ui.Model;
6+
import org.springframework.web.bind.annotation.PathVariable;
7+
import org.springframework.web.bind.annotation.RequestMapping;
8+
9+
@Slf4j
10+
@Controller
11+
public class WebSocketController {
12+
13+
@RequestMapping("/websocket/{name}")
14+
public String webSocket(@PathVariable String name, Model model) {
15+
try {
16+
log.info("跳转到websocket的页面上");
17+
model.addAttribute("username", name);
18+
return "websocket";
19+
} catch (Exception e) {
20+
log.info("跳转到websocket的页面上发生异常,异常信息是:" + e.getMessage());
21+
return "error";
22+
}
23+
}
24+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+

0 commit comments

Comments
 (0)