First of all, I was reading this chat room-> this blogger's article <-played the code with him again. If anyone sees the blog post I wrote, please go to this blogger to see the details. I just upload the code and make code notes.
After I read the blogger ’s blog, I probably think of the following ideas:
The first is to import dependencies, using a websocket function of HTML5:
< dependency>
< groupId> org.springframework.boot</ groupId>
< artifactId> spring-boot-starter-websocket</ artifactId>
</ dependency>
Next is to add and configure WebSocketConfig.java
package com. example. java. webstock. demo. configWeb;
import org. springframework. context. annotation. Bean;
import org. springframework. context. annotation. Configuration;
import org. springframework. web. socket. server. standard. ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter ( ) {
return new ServerEndpointExporter ( ) ;
}
}
Then there is the Controller layer on the server side:
First make a simple test class
package com. example. java. webstock. demo. configServer;
import org. springframework. stereotype. Component;
import javax. websocket. *;
import javax. websocket. server. PathParam;
import javax. websocket. server. ServerEndpoint;
import java. io. IOException;
@Component
@ServerEndpoint ( "/websocket/{sid}" )
public class WebSocketServerController {
@OnMessage
public void onMessage ( Session session, String message) {
try {
session. getBasicRemote ( ) . sendText ( message) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
}
@OnOpen
public void onOpen ( @PathParam ( "sid" ) String sid) {
System. out. println ( "Client connected" ) ;
}
@OnClose
public void onClose ( ) {
System. out. println ( "Connection closed" ) ;
}
@OnError
public void OnError ( Throwable error) {
System. out. println ( "Connection error" ) ;
}
}
This is the front-end code index.html
<!DOCTYPE html>
< html>
< head>
< meta charset = " UTF-8" >
< title> Testing websockets</ title>
</ head>
< body>
< div>
< textarea rows = " 3" cols = " 20" id = " content" > </ textarea>
< br>
< input type = " submit" value = " Start" onclick = " start()" />
</ div>
< div id = " messages" > </ div>
< script type = " text/javascript" >
var webSocket =
new WebSocket ( 'ws://localhost:8080/websocket/2020' ) ;
webSocket. onerror = function ( event) {
onError ( event)
} ;
webSocket. onopen = function ( event) {
onOpen ( event)
} ;
webSocket. onmessage = function ( event) {
onMessage ( event)
} ;
webSocket. onclose = function ( event) {
onClose ( event)
} ;
function onMessage ( event) {
document. getElementById ( 'messages' ) . innerHTML
+= '<br />' + event. data;
}
function onOpen ( event) {
document. getElementById ( 'messages' ) . innerHTML
= 'Connection established' ;
}
function onError ( event) {
alert ( event) ;
}
function onClose ( event) {
alert ( event) ;
}
function start ( ) {
var text = document. getElementById ( 'content' ) . value;
webSocket. send ( text) ;
}
</ script>
</ body>
</ html>
This is the test result:
Then this is the function of realizing multiplayer online chat
GroupChatController.java
package com. example. java. webstock. demo. configServer;
import lombok. extern. slf4j. Slf4j;
import org. springframework. stereotype. Component;
import javax. websocket. *;
import javax. websocket. server. PathParam;
import javax. websocket. server. ServerEndpoint;
import java. io. IOException;
import java. util. ArrayList;
import java. util. List;
import java. util. concurrent. ConcurrentHashMap;
@Slf4j
@Component
@ServerEndpoint ( "/groupChat/{sid}/{username}" )
public class GroupChatController {
private static ConcurrentHashMap< String, List< Session> > groupMemberInfoMap = new ConcurrentHashMap < > ( ) ;
@OnMessage
public void onMessage ( @PathParam ( "sid" ) String sid, @PathParam ( "username" ) String username, String message ) {
List< Session> sessionList = groupMemberInfoMap. get ( sid) ;
sessionList. forEach ( item - > {
try {
String text = username+ " : " + message;
item. getBasicRemote ( ) . sendText ( text) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
} ) ;
}
@OnOpen
public void onOpen ( Session session, @PathParam ( "sid" ) String sid) {
List< Session> sessionList = groupMemberInfoMap. get ( sid) ;
if ( sessionList == null) {
sessionList = new ArrayList < > ( ) ;
groupMemberInfoMap. put ( sid, sessionList) ;
}
sessionList. add ( session) ;
log. info ( "Connection connected" ) ;
log. info ( "sid: {}, sessionList size: {}" , sid, sessionList. size ( ) ) ;
}
@OnClose
public void onClose ( Session session, @PathParam ( "sid" ) String sid) {
List< Session> sessionList = groupMemberInfoMap. get ( sid) ;
sessionList. remove ( session) ;
log. info ( "Connection closed" ) ;
log. info ( "sid: {}, sessionList size: {}" , sid, sessionList. size ( ) ) ;
}
@OnError
public void OnError ( Throwable error) {
log. info ( "Connection error" ) ;
}
}
I encountered a pit here. The blogger's slf4j import was not used in pom.xml. I went to the settings and imported lombok to solve it. This is a log.
Then index.html
<!DOCTYPE html>
< html>
< head>
< meta charset = " UTF-8" >
< title> Testing websockets</ title>
</ head>
< body>
< div>
< input type = " text" id = " sid" placeholder = " 请输入房间" /> < br>
< input type = " text" id = " nickname" placeholder = " 请输入昵称" /> < br>
< input type = " submit" value = " 连接" onclick = " connect()" /> < br>
< textarea rows = " 3" cols = " 20" id = " content" > </ textarea> < br>
< input type = " submit" value = " 发送" onclick = " start()" />
< br>
</ div>
< div id = " messages" > </ div>
< script type = " text/javascript" >
var webSocket = null ;
function onMessage ( event) {
document. getElementById ( 'messages' ) . innerHTML
+= '<br />' + event. data;
}
function onOpen ( event) {
document. getElementById ( 'messages' ) . innerHTML
= 'Connection established' ;
}
function onError ( event) {
alert ( "发生错误" ) ;
}
function onClose ( event) {
alert ( "连接关闭" ) ;
}
function connect ( ) {
var sid = document. getElementById ( 'sid' ) . value;
var nickname = document. getElementById ( 'nickname' ) . value;
if ( url == '' || nickname == '' ) {
alert ( "房间号和用户名不能为空" ) ;
return ;
}
var serverHot = window. location. host;
var url = 'ws://localhost:8081/groupChat/' + sid + '/' + nickname;
webSocket = new WebSocket ( url) ;
webSocket. onerror = function ( event) {
onError ( event)
} ;
webSocket. onopen = function ( event) {
onOpen ( event)
} ;
webSocket. onmessage = function ( event) {
onMessage ( event)
} ;
webSocket. onclose = function ( event) {
onClose ( event)
} ;
}
function start ( ) {
var text = document. getElementById ( 'content' ) . value;
webSocket. send ( text) ;
document. getElementById ( 'content' ) . value = '' ;
}
</ script>
</ body>
</ html>
This is the test result