Spring Boot实战之netty-socketio实现简单聊天室(给指定用户推送消息)

spring Boot实战之netty-socketio实现简单聊天室(给指定用户推送消息)


网上好多例子都是群发的,本文实现一对一的发送,给指定客户端进行消息推送


1、本文使用到netty-socketio开源库,以及MySQL,所以首先在pom.xml中添加相应的依赖库

[html]  view plain  copy
  1. <dependency>  
  2.         <groupId>com.corundumstudio.socketio</groupId>  
  3.         <artifactId>netty-socketio</artifactId>  
  4.         <version>1.7.11</version>  
  5. </dependency>  
  6. <dependency>  
  7.         <groupId>org.springframework.boot</groupId>  
  8.     <artifactId>spring-boot-starter-data-jpa</artifactId>  
  9. </dependency>  
  10. <dependency>  
  11.     <groupId>mysql</groupId>  
  12.     <artifactId>mysql-connector-java</artifactId>  
  13. </dependency>  

2、修改application.properties, 添加端口及主机数据库连接等相关配置,

[html]  view plain  copy
  1. wss.server.port=8081  
  2. wss.server.host=localhost  
  3.   
  4. spring.datasource.url = jdbc:mysql://127.0.0.1:3306/springlearn  
  5. spring.datasource.username = root  
  6. spring.datasource.password = root  
  7. spring.datasource.driverClassName = com.mysql.jdbc.Driver  
  8.   
  9. # Specify the DBMS  
  10. spring.jpa.database = MYSQL  
  11. # Show or not log for each sql query  
  12. spring.jpa.show-sql = true  
  13. # Hibernate ddl auto (create, create-drop, update)  
  14. spring.jpa.hibernate.ddl-auto = update  
  15. # Naming strategy  
  16. spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy  
  17. # stripped before adding them to the entity manager)  
  18. spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect  

3、修改Application文件,添加nettysocket的相关配置信息

[java]  view plain  copy
  1. package com.xiaofangtech.sunt;  
  2.   
  3. import org.springframework.beans.factory.annotation.Value;  
  4. import org.springframework.boot.SpringApplication;  
  5. import org.springframework.boot.autoconfigure.SpringBootApplication;  
  6. import org.springframework.context.annotation.Bean;  
  7.   
  8. import com.corundumstudio.socketio.AuthorizationListener;  
  9. import com.corundumstudio.socketio.Configuration;  
  10. import com.corundumstudio.socketio.HandshakeData;  
  11. import com.corundumstudio.socketio.SocketIOServer;  
  12. import com.corundumstudio.socketio.annotation.SpringAnnotationScanner;  
  13.   
  14. @SpringBootApplication  
  15. public class NettySocketSpringApplication {  
  16.   
  17.     @Value("${wss.server.host}")  
  18.     private String host;  
  19.   
  20.     @Value("${wss.server.port}")  
  21.     private Integer port;  
  22.       
  23.     @Bean  
  24.     public SocketIOServer socketIOServer()   
  25.     {  
  26.         Configuration config = new Configuration();  
  27.         config.setHostname(host);  
  28.         config.setPort(port);  
  29.           
  30.         //该处可以用来进行身份验证  
  31.         config.setAuthorizationListener(new AuthorizationListener() {  
  32.             @Override  
  33.             public boolean isAuthorized(HandshakeData data) {  
  34.                 //http://localhost:8081?username=test&password=test  
  35.                 //例如果使用上面的链接进行connect,可以使用如下代码获取用户密码信息,本文不做身份验证  
  36. //              String username = data.getSingleUrlParam("username");  
  37. //              String password = data.getSingleUrlParam("password");  
  38.                 return true;  
  39.             }  
  40.         });  
  41.           
  42.         final SocketIOServer server = new SocketIOServer(config);  
  43.         return server;  
  44.     }  
  45.       
  46.     @Bean  
  47.     public SpringAnnotationScanner springAnnotationScanner(SocketIOServer socketServer) {  
  48.         return new SpringAnnotationScanner(socketServer);  
  49.     }  
  50.       
  51.     public static void main(String[] args) {  
  52.         SpringApplication.run(NettySocketSpringApplication.class, args);  
  53.     }  
  54. }  

4、添加消息结构类MessageInfo.java

[java]  view plain  copy
  1. package com.xiaofangtech.sunt.message;  
  2.   
  3. public class MessageInfo {  
  4.     //源客户端id  
  5.     private String sourceClientId;  
  6.     //目标客户端id  
  7.     private String targetClientId;  
  8.     //消息类型  
  9.     private String msgType;  
  10.     //消息内容  
  11.     private String msgContent;  
  12.       
  13.     public String getSourceClientId() {  
  14.         return sourceClientId;  
  15.     }  
  16.     public void setSourceClientId(String sourceClientId) {  
  17.         this.sourceClientId = sourceClientId;  
  18.     }  
  19.     public String getTargetClientId() {  
  20.         return targetClientId;  
  21.     }  
  22.     public void setTargetClientId(String targetClientId) {  
  23.         this.targetClientId = targetClientId;  
  24.     }  
  25.     public String getMsgType() {  
  26.         return msgType;  
  27.     }  
  28.     public void setMsgType(String msgType) {  
  29.         this.msgType = msgType;  
  30.     }  
  31.     public String getMsgContent() {  
  32.         return msgContent;  
  33.     }  
  34.     public void setMsgContent(String msgContent) {  
  35.         this.msgContent = msgContent;  
  36.     }  
  37. }  

5、添加客户端信息,用来存放客户端的sessionid

[java]  view plain  copy
  1. package com.xiaofangtech.sunt.bean;  
  2.   
  3. import java.util.Date;  
  4.   
  5. import javax.persistence.Entity;  
  6. import javax.persistence.Id;  
  7. import javax.persistence.Table;  
  8. import javax.validation.constraints.NotNull;  
  9.   
  10. @Entity  
  11. @Table(name="t_clientinfo")  
  12. public class ClientInfo {  
  13.     @Id  
  14.     @NotNull  
  15.     private String clientid;  
  16.     private Short connected;  
  17.     private Long mostsignbits;  
  18.     private Long leastsignbits;  
  19.     private Date lastconnecteddate;  
  20.     public String getClientid() {  
  21.         return clientid;  
  22.     }  
  23.     public void setClientid(String clientid) {  
  24.         this.clientid = clientid;  
  25.     }  
  26.     public Short getConnected() {  
  27.         return connected;  
  28.     }  
  29.     public void setConnected(Short connected) {  
  30.         this.connected = connected;  
  31.     }  
  32.     public Long getMostsignbits() {  
  33.         return mostsignbits;  
  34.     }  
  35.     public void setMostsignbits(Long mostsignbits) {  
  36.         this.mostsignbits = mostsignbits;  
  37.     }  
  38.     public Long getLeastsignbits() {  
  39.         return leastsignbits;  
  40.     }  
  41.     public void setLeastsignbits(Long leastsignbits) {  
  42.         this.leastsignbits = leastsignbits;  
  43.     }  
  44.     public Date getLastconnecteddate() {  
  45.         return lastconnecteddate;  
  46.     }  
  47.     public void setLastconnecteddate(Date lastconnecteddate) {  
  48.         this.lastconnecteddate = lastconnecteddate;  
  49.     }  
  50.       
  51. }  

6、添加查询数据库接口ClientInfoRepository.java

[java]  view plain  copy
  1. package com.xiaofangtech.sunt.repository;  
  2.   
  3. import org.springframework.data.repository.CrudRepository;  
  4.   
  5. import com.xiaofangtech.sunt.bean.ClientInfo;  
  6.   
  7. public interface ClientInfoRepository extends CrudRepository<ClientInfo, String>{  
  8.     ClientInfo findClientByclientid(String clientId);  
  9. }  


7、添加消息处理类MessageEventHandler.Java

[java]  view plain  copy
  1. package com.xiaofangtech.sunt.message;  
  2.   
  3. import java.util.Date;  
  4. import java.util.UUID;  
  5.   
  6. import org.springframework.beans.factory.annotation.Autowired;  
  7. import org.springframework.stereotype.Component;  
  8.   
  9. import com.corundumstudio.socketio.AckRequest;  
  10. import com.corundumstudio.socketio.SocketIOClient;  
  11. import com.corundumstudio.socketio.SocketIOServer;  
  12. import com.corundumstudio.socketio.annotation.OnConnect;  
  13. import com.corundumstudio.socketio.annotation.OnDisconnect;  
  14. import com.corundumstudio.socketio.annotation.OnEvent;  
  15. import com.xiaofangtech.sunt.bean.ClientInfo;  
  16. import com.xiaofangtech.sunt.repository.ClientInfoRepository;  
  17.   
  18. @Component  
  19. public class MessageEventHandler   
  20. {  
  21.     private final SocketIOServer server;  
  22.       
  23.     @Autowired  
  24.     private ClientInfoRepository clientInfoRepository;  
  25.       
  26.     @Autowired  
  27.     public MessageEventHandler(SocketIOServer server)   
  28.     {  
  29.         this.server = server;  
  30.     }  
  31.     //添加connect事件,当客户端发起连接时调用,本文中将clientid与sessionid存入数据库  
  32.     //方便后面发送消息时查找到对应的目标client,  
  33.     @OnConnect  
  34.     public void onConnect(SocketIOClient client)  
  35.     {  
  36.         String clientId = client.getHandshakeData().getSingleUrlParam("clientid");  
  37.         ClientInfo clientInfo = clientInfoRepository.findClientByclientid(clientId);  
  38.         if (clientInfo != null)  
  39.         {  
  40.             Date nowTime = new Date(System.currentTimeMillis());  
  41.             clientInfo.setConnected((short)1);  
  42.             clientInfo.setMostsignbits(client.getSessionId().getMostSignificantBits());  
  43.             clientInfo.setLeastsignbits(client.getSessionId().getLeastSignificantBits());  
  44.             clientInfo.setLastconnecteddate(nowTime);  
  45.             clientInfoRepository.save(clientInfo);  
  46.         }  
  47.     }  
  48.       
  49.     //添加@OnDisconnect事件,客户端断开连接时调用,刷新客户端信息  
  50.     @OnDisconnect  
  51.     public void onDisconnect(SocketIOClient client)  
  52.     {  
  53.         String clientId = client.getHandshakeData().getSingleUrlParam("clientid");  
  54.         ClientInfo clientInfo = clientInfoRepository.findClientByclientid(clientId);  
  55.         if (clientInfo != null)  
  56.         {  
  57.             clientInfo.setConnected((short)0);  
  58.             clientInfo.setMostsignbits(null);  
  59.             clientInfo.setLeastsignbits(null);  
  60.             clientInfoRepository.save(clientInfo);  
  61.         }  
  62.     }  
  63.       
  64.     //消息接收入口,当接收到消息后,查找发送目标客户端,并且向该客户端发送消息,且给自己发送消息  
  65.     @OnEvent(value = "messageevent")  
  66.     public void onEvent(SocketIOClient client, AckRequest request, MessageInfo data)   
  67.     {  
  68.         String targetClientId = data.getTargetClientId();  
  69.         ClientInfo clientInfo = clientInfoRepository.findClientByclientid(targetClientId);  
  70.         if (clientInfo != null && clientInfo.getConnected() != 0)  
  71.         {  
  72.             UUID uuid = new UUID(clientInfo.getMostsignbits(), clientInfo.getLeastsignbits());  
  73.             System.out.println(uuid.toString());  
  74.             MessageInfo sendData = new MessageInfo();  
  75.             sendData.setSourceClientId(data.getSourceClientId());  
  76.             sendData.setTargetClientId(data.getTargetClientId());  
  77.             sendData.setMsgType("chat");  
  78.             sendData.setMsgContent(data.getMsgContent());  
  79.             client.sendEvent("messageevent", sendData);  
  80.             server.getClient(uuid).sendEvent("messageevent", sendData);  
  81.         }  
  82.           
  83.     }  
  84. }  

8、添加ServerRunner.java

[java]  view plain  copy
  1. package com.xiaofangtech.sunt.message;  
  2.   
  3. import org.springframework.beans.factory.annotation.Autowired;  
  4. import org.springframework.boot.CommandLineRunner;  
  5. import org.springframework.stereotype.Component;  
  6.   
  7. import com.corundumstudio.socketio.SocketIOServer;  
  8.   
  9. @Component  
  10. public class ServerRunner implements CommandLineRunner {  
  11.     private final SocketIOServer server;  
  12.   
  13.     @Autowired  
  14.     public ServerRunner(SocketIOServer server) {  
  15.         this.server = server;  
  16.     }  
  17.   
  18.     @Override  
  19.     public void run(String... args) throws Exception {  
  20.         server.start();  
  21.     }  
  22. }  

9、工程结构



10、运行测试

1) 添加基础数据,数据库中预置3个客户端testclient1,testclient2,testclient3



2) 创建客户端文件index.html,index2.html,index3.html分别代表testclient1 testclient2 testclient3三个用户

本文直接修改的https://github.com/mrniko/netty-socketio-demo/tree/master/client 中的index.html文件

其中clientid为发送者id, targetclientid为目标方id,本文简单的将发送方和接收方写死在html文件中

使用 以下代码进行连接

[html]  view plain  copy
  1. io.connect('http://localhost:8081?clientid='+clientid);  

index.html 文件内容如下

[html]  view plain  copy
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.   
  5.         <meta charset="utf-8" />  
  6.   
  7.         <title>Demo Chat</title>  
  8.   
  9.         <link href="bootstrap.css" rel="stylesheet">  
  10.   
  11.     <style>  
  12.         body {  
  13.             padding:20px;  
  14.         }  
  15.         #console {  
  16.             height: 400px;  
  17.             overflow: auto;  
  18.         }  
  19.         .username-msg {color:orange;}  
  20.         .connect-msg {color:green;}  
  21.         .disconnect-msg {color:red;}  
  22.         .send-msg {color:#888}  
  23.     </style>  
  24.   
  25.   
  26.     <script src="js/socket.io/socket.io.js"></script>  
  27.         <script src="js/moment.min.js"></script>  
  28.         <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>  
  29.   
  30.     <script>  
  31.   
  32.         var clientid = 'testclient1';  
  33.         var targetClientId'testclient2';  
  34.           
  35.         var socket =  io.connect('http://localhost:8081?clientid='+clientid);  
  36.   
  37.         socket.on('connect', function() {  
  38.             output('<span class="connect-msg">Client has connected to the server!</span>');  
  39.         });  
  40.   
  41.         socket.on('messageevent', function(data) {  
  42.             output('<span class="username-msg">' + data.sourceClientId + ':</span> ' + data.msgContent);  
  43.         });  
  44.   
  45.         socket.on('disconnect', function() {  
  46.             output('<span class="disconnect-msg">The client has disconnected!</span>');  
  47.         });  
  48.   
  49.                 function sendDisconnect() {  
  50.                         socket.disconnect();  
  51.                 }  
  52.   
  53.         function sendMessage() {  
  54.                         var message = $('#msg').val();  
  55.                         $('#msg').val('');  
  56.   
  57.                         var jsonObject = {sourceClientId: clientid,  
  58.                                           targetClientId: targetClientId,  
  59.                                           msgType: 'chat',  
  60.                                           msgContent: message};  
  61.                         socket.emit('messageevent', jsonObject);  
  62.         }  
  63.   
  64.         function output(message) {  
  65.                         var currentTime = "<span class='time'>" +  moment().format('HH:mm:ss.SSS') + "</span>";  
  66.                         var element = $("<div>" + currentTime + " " + message + "</div>");  
  67.             $('#console').prepend(element);  
  68.         }  
  69.   
  70.         $(document).keydown(function(e){  
  71.             if(e.keyCode == 13) {  
  72.                 $('#send').click();  
  73.             }  
  74.         });  
  75.     </script>  
  76. </head>  
  77.   
  78. <body>  
  79.   
  80.     <h1>Netty-socketio Demo Chat</h1>  
  81.   
  82.     <br/>  
  83.   
  84.     <div id="console" class="well">  
  85.     </div>  
  86.   
  87.         <form class="well form-inline" onsubmit="return false;">  
  88.            <input id="msg" class="input-xlarge" type="text" placeholder="Type something..."/>  
  89.            <button type="button" onClick="sendMessage()" class="btn" id="send">Send</button>  
  90.            <button type="button" onClick="sendDisconnect()" class="btn">Disconnect</button>  
  91.         </form>  
  92.   
  93.   
  94.   
  95. </body>  
  96.   
  97. </html>  

3、本例测试时

testclient1 发送消息给 testclient2

testclient2 发送消息给 testclient1

testclient3发送消息给testclient1

运行结果如下




  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值