SpringBoot实战之netty-socketio实现简单聊天室(给指定⽤户推送消息)⽹上好多例⼦都是发的,本⽂实现⼀对⼀的发送,给指定客户端进⾏消息推送
1、本⽂使⽤到netty-socketio开源库,以及MySQL,所以⾸先在l中添加相应的依赖库
<dependency>
<groupId&undumstudio.socketio</groupId>
<artifactId>netty-socketio</artifactId>
<version>1.7.11</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
2、修改application.properties, 添加端⼝及主机数据库连接等相关配置,
wss.server.port=8081
wss.server.host=localhost
spring.datasource.url = jdbc:mysql://127.0.0.1:3306/springlearn
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.driverClassName = sql.jdbc.Driver
# Specify the DBMS
spring.jpa.database = MYSQL
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update
# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
# stripped before adding them to the entity manager)
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
3、修改Application⽂件,添加nettysocket的相关配置信息
package com.xiaofangtech.sunt;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import t.annotation.Bean;
undumstudio.socketio.AuthorizationListener;
undumstudio.socketio.Configuration;
undumstudio.socketio.HandshakeData;
undumstudio.socketio.SocketIOServer;
undumstudio.socketio.annotation.SpringAnnotationScanner;
@SpringBootApplication
public class NettySocketSpringApplication {
@Value("${wss.server.host}")
private String host;
@Value("${wss.server.port}")
private Integer port;
@Bean
public SocketIOServer socketIOServer()
{
Configuration config = new Configuration();
config.setHostname(host);
config.setPort(port);
/
/该处可以⽤来进⾏⾝份验证
config.setAuthorizationListener(new AuthorizationListener() {
@Override
public boolean isAuthorized(HandshakeData data) {
//localhost:8081?username=test&password=test
//例如果使⽤上⾯的链接进⾏connect,可以使⽤如下代码获取⽤户密码信息,本⽂不做⾝份验证
//      String username = SingleUrlParam("username");
//      String password = SingleUrlParam("password");
return true;
}
});
final SocketIOServer server = new SocketIOServer(config);
return server;
}
@Bean
public SpringAnnotationScanner springAnnotationScanner(SocketIOServer socketServer) {
return new SpringAnnotationScanner(socketServer);
}
public static void main(String[] args) {
SpringApplication.run(NettySocketSpringApplication.class, args);
}
}
4、添加消息结构类MessageInfo.java
package com.ssage;
public class MessageInfo {
//源客户端id
private String sourceClientId;
//⽬标客户端id
private String targetClientId;
//消息类型
private String msgType;
//消息内容
private String msgContent;
public String getSourceClientId() {
return sourceClientId;
}
public void setSourceClientId(String sourceClientId) {
this.sourceClientId = sourceClientId;
}
public String getTargetClientId() {
return targetClientId;
}
public void setTargetClientId(String targetClientId) {
this.targetClientId = targetClientId;
}
public String getMsgType() {
return msgType;
}
public void setMsgType(String msgType) {
this.msgType = msgType;
}
public String getMsgContent() {
return msgContent;
}
public void setMsgContent(String msgContent) {
this.msgContent = msgContent;
}
}
5、添加客户端信息,⽤来存放客户端的sessionid
package com.xiaofangtech.sunt.bean;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import straints.NotNull;
@Entity
@Table(name="t_clientinfo")
public class ClientInfo {
@Id
@NotNull
private String clientid;
private Short connected;
private Long mostsignbits;
private Long leastsignbits;
private Date lastconnecteddate;
public String getClientid() {
return clientid;
}
public void setClientid(String clientid) {
this.clientid = clientid;
}
public Short getConnected() {
return connected;
}
public void setConnected(Short connected) {
}
public Long getMostsignbits() {
return mostsignbits;
}
public void setMostsignbits(Long mostsignbits) {
}
public Long getLeastsignbits() {
return leastsignbits;
}
public void setLeastsignbits(Long leastsignbits) {
this.leastsignbits = leastsignbits;
}
public Date getLastconnecteddate() {
return lastconnecteddate;
}
public void setLastconnecteddate(Date lastconnecteddate) {
this.lastconnecteddate = lastconnecteddate;
}
}
6、添加查询数据库接⼝ClientInfoRepository.java
package com.pository;
import org.pository.CrudRepository;
import com.xiaofangtech.sunt.bean.ClientInfo;
public interface ClientInfoRepository extends CrudRepository<ClientInfo, String>{  ClientInfo findClientByclientid(String clientId);
}
7、添加消息处理类MessageEventHandler.Java
package com.ssage;
import java.util.Date;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
undumstudio.socketio.AckRequest;
undumstudio.socketio.SocketIOClient;
undumstudio.socketio.SocketIOServer;
undumstudio.socketio.annotation.OnConnect;
undumstudio.socketio.annotation.OnDisconnect;
undumstudio.socketio.annotation.OnEvent;
import com.xiaofangtech.sunt.bean.ClientInfo;
import com.pository.ClientInfoRepository;
@Component
public class MessageEventHandler
{
private final SocketIOServer server;
@Autowired
private ClientInfoRepository clientInfoRepository;
@Autowired
public MessageEventHandler(SocketIOServer server)
{
this.server = server;
}
//添加connect事件,当客户端发起连接时调⽤,本⽂中将clientid与sessionid存⼊数据库
//⽅便后⾯发送消息时查到对应的⽬标client,
@OnConnect
public void onConnect(SocketIOClient client)
{
String clientId = HandshakeData().getSingleUrlParam("clientid");
ClientInfo clientInfo = clientInfoRepository.findClientByclientid(clientId);
if (clientInfo != null)
{
Date nowTime = new Date(System.currentTimeMillis());
clientInfo.setConnected((short)1);
clientInfo.SessionId().getMostSignificantBits());
clientInfo.SessionId().getLeastSignificantBits());
clientInfo.setLastconnecteddate(nowTime);
clientInfoRepository.save(clientInfo);
}
}
/
/添加@OnDisconnect事件,客户端断开连接时调⽤,刷新客户端信息
@OnDisconnect
public void onDisconnect(SocketIOClient client)
{
String clientId = HandshakeData().getSingleUrlParam("clientid");
ClientInfo clientInfo = clientInfoRepository.findClientByclientid(clientId);
if (clientInfo != null)
{
clientInfo.setConnected((short)0);
clientInfo.setMostsignbits(null);
clientInfo.setLeastsignbits(null);
clientInfoRepository.save(clientInfo);
}
}
//消息接收⼊⼝,当接收到消息后,查发送⽬标客户端,并且向该客户端发送消息,且给⾃⼰发送消息  @OnEvent(value = "messageevent")
public void onEvent(SocketIOClient client, AckRequest request, MessageInfo data)
{
String targetClientId = TargetClientId();
ClientInfo clientInfo = clientInfoRepository.findClientByclientid(targetClientId);
if (clientInfo != null && Connected() != 0)
{
UUID uuid = new Mostsignbits(), Leastsignbits());
System.out.String());
MessageInfo sendData = new MessageInfo();
sendData.SourceClientId());
sendData.TargetClientId());
sendData.setMsgType("chat");
sendData.MsgContent());
client.sendEvent("messageevent", sendData);
}
}
}
8、添加ServerRunner.java
package com.ssage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
undumstudio.socketio.SocketIOServer;
@Component
public class ServerRunner implements CommandLineRunner {
private final SocketIOServer server;
@Autowired
public ServerRunner(SocketIOServer server) {
this.server = server;
}
@Override
public void args) throws Exception {
server.start();
}
}
9、⼯程结构
10、运⾏测试
1)添加基础数据,数据库中预置3个客户端testclient1,testclient2,testclient3
2) 创建客户端⽂件index.html,index2.html,index3.html分别代表testclient1 testclient2 testclient3三个⽤户其中clientid为发送者id, targetclientid为⽬标⽅id,本⽂简单的将发送⽅和接收⽅写死在html⽂件中
使⽤以下代码进⾏连接
index.html ⽂件内容如下
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Demo Chat</title>
<link href="bootstrap.css" rel="external nofollow" rel="stylesheet">
<style>
body {
padding:20px;
}
#console {
height: 400px;
overflow: auto;
}
.username-msg {color:orange;}
.connect-msg {color:green;}
.disconnect-msg {color:red;}
.send-msg {color:#888}
</style>
<script src="js/socket.io/socket.io.js"></script>
<script src="js/moment.min.js"></script>
<script src="code.jquery/jquery-1.10.1.min.js"></script>
<script>
var clientid = 'testclient1';
var targetClientId= 'testclient2';
var socket = io.connect('localhost:8081?clientid='+clientid);
<('connect', function() {
output('<span class="connect-msg">Client has connected to the server!</span>');
});
<('messageevent', function(data) {
output('<span class="username-msg">' + data.sourceClientId + ':</span> ' + data.msgContent);
});
<('disconnect', function() {
output('<span class="disconnect-msg">The client has disconnected!</span>');
});
socket编程聊天室基本流程
function sendDisconnect() {
socket.disconnect();
}
function sendMessage() {
var message = $('#msg').val();
$('#msg').val('');
var jsonObject = {sourceClientId: clientid,
targetClientId: targetClientId,
msgType: 'chat',
msgContent: message};
}
function output(message) {
var currentTime = "<span class='time'>" + moment().format('HH:mm:ss.SSS') + "</span>";
var element = $("<div>" + currentTime + " " + message + "</div>");
$('#console').prepend(element);
}
$(document).keydown(function(e){
if(e.keyCode == 13) {
$('#send').click();
}
});
</script>
</head>
<body>
<h1>Netty-socketio Demo Chat</h1>
<br/>
<div id="console" class="well">
</div>
<form class="well form-inline" onsubmit="return false;">
<input id="msg" class="input-xlarge" type="text" placeholder=""/>
<button type="button" onClick="sendMessage()" class="btn" id="send">Send</button>
<button type="button" onClick="sendDisconnect()" class="btn">Disconnect</button>
</form>
</body>
</html>
3、本例测试时
testclient1 发送消息给 testclient2
testclient2 发送消息给 testclient1
testclient3发送消息给testclient1
运⾏结果如下
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。