引言
对于某些项目来说,需要用户之间进行实时交流。本博客记录了实现群聊+单聊的功能的步骤。
项目结构
集成步骤
1、pom文件
<!--websocket依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2、config文件
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
3、entity类
@Data
public class SocketMsg {
private int type;
private String fromUser;
private String toUser;
private String msg;
}
4、具体实现类
import com.fasterxml.jackson.databind.ObjectMapper;
import com.information.entity.SocketMsg;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;
@Component
@ServerEndpoint(value = "/websocket/{nickname}")
public class WebSocketServer{
private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<>();
private Session session;
private String nickname;
private static Map<String,Session> map = new HashMap<String, Session>();
@OnOpen
public void onOpen(Session session,@PathParam("nickname") String nickname) {
this.session = session;
this.nickname=nickname;
map.put(session.getId(), session);
webSocketSet.add(this);
System.out.println("有新连接加入:"+nickname+",当前在线人数为" + webSocketSet.size());
this.session.getAsyncRemote().sendText("恭喜"+nickname+"成功连接上WebSocket(其频道号:"+session.getId()+")-->当前在线人数为:"+webSocketSet.size());
}
@OnClose
public void onClose() {
webSocketSet.remove(this);
System.out.println("有一连接关闭!当前在线人数为" + webSocketSet.size());
}
@OnMessage
public void onMessage(String message, Session session,@PathParam("nickname") String nickname) {
System.out.println("来自客户端的消息-->"+nickname+": " + message);
ObjectMapper objectMapper = new ObjectMapper();
SocketMsg socketMsg;
try {
socketMsg = objectMapper.readValue(message, SocketMsg.class);
if(socketMsg.getType() == 1){
socketMsg.setFromUser(session.getId());
Session fromSession = map.get(socketMsg.getFromUser());
Session toSession = map.get(socketMsg.getToUser());
if(toSession != null){
fromSession.getAsyncRemote().sendText(nickname+":"+socketMsg.getMsg());
toSession.getAsyncRemote().sendText(nickname+":"+socketMsg.getMsg());
}else{
fromSession.getAsyncRemote().sendText("系统消息:对方不在线或者您输入的频道号不对");
}
}else{
broadcast(nickname+": "+socketMsg.getMsg());
}
} catch (Exception e) {
e.printStackTrace();
}
}
@OnError
public void onError(Session session, Throwable error) {
System.out.println("发生错误");
error.printStackTrace();
}
public void broadcast(String message) {
for (MyWebSocket item : webSocketSet) {
item.session.getAsyncRemote().sendText(message);
}
}
}
5、html
<body>
<div>
<input type="text" id="nickname"/>
<button onclick="connectWebSocket()">连接WebSocket</button>
<button onclick="closeWebSocket()">断开连接</button>
<hr/>
<br/>
消息:<input id="text" type="text"/>
频道号:<input id="toUser" type="text"/>
<button onclick="send()">发送消息</button>
<div id="message"></div>
</div>
<script type="text/javascript">
var websocket = null;
function connectWebSocket() {
var nickname = document.getElementById("nickname").value;
if (nickname === "") {
alert("请输入昵称");
return;
}
if ('WebSocket' in window) {
websocket = new WebSocket("ws://localhost:8080/websocket/" + nickname);
} else {
alert('Not support websocket')
}
websocket.onerror = function () {
setMessageInnerHTML("error");
};
websocket.onopen = function (event) {
setMessageInnerHTML("Loc MSG: 成功建立连接");
}
websocket.onmessage = function (event) {
setMessageInnerHTML(event.data);
}
websocket.onclose = function () {
setMessageInnerHTML("Loc MSG:关闭连接");
}
window.onbeforeunload = function () {
websocket.close();
}
}
function setMessageInnerHTML(innerHTML) {
document.getElementById('message').innerHTML += innerHTML + '<br/>';
}
function closeWebSocket() {
websocket.close();
}
function send() {
var message = document.getElementById('text').value;
var toUser = document.getElementById('toUser').value;
var socketMsg = {msg: message, toUser: toUser};
if (toUser == '') {
socketMsg.type = 0;
} else {
socketMsg.type = 1;
}
websocket.send(JSON.stringify(socketMsg));
}
</script>
</body>
测试结果
群聊: 单聊
扩展资料
1、计算机网络通信之探究Socket通信 2、计算机网络通信之探究TCP/IP协议
|