網(wǎng)上好多例子都是群發(fā)的,本文實(shí)現(xiàn)一對(duì)一的發(fā)送,給指定客戶(hù)端進(jìn)行消息推送
成都創(chuàng)新互聯(lián)于2013年成立,先為昔陽(yáng)等服務(wù)建站,昔陽(yáng)等地企業(yè),進(jìn)行企業(yè)商務(wù)咨詢(xún)服務(wù)。為昔陽(yáng)企業(yè)網(wǎng)站制作PC+手機(jī)+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問(wèn)題。
1、本文使用到netty-socketio開(kāi)源庫(kù),以及MySQL,所以首先在pom.xml中添加相應(yīng)的依賴(lài)庫(kù)
com.corundumstudio.socketio netty-socketio 1.7.11 org.springframework.boot spring-boot-starter-data-jpa mysql mysql-connector-java
2、修改application.properties, 添加端口及主機(jī)數(shù)據(jù)庫(kù)連接等相關(guān)配置,
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 = com.mysql.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的相關(guān)配置信息
package com.xiaofangtech.sunt; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import com.corundumstudio.socketio.AuthorizationListener; import com.corundumstudio.socketio.Configuration; import com.corundumstudio.socketio.HandshakeData; import com.corundumstudio.socketio.SocketIOServer; import com.corundumstudio.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); //該處可以用來(lái)進(jìn)行身份驗(yàn)證 config.setAuthorizationListener(new AuthorizationListener() { @Override public boolean isAuthorized(HandshakeData data) { //http://localhost:8081?username=test&password=test //例如果使用上面的鏈接進(jìn)行connect,可以使用如下代碼獲取用戶(hù)密碼信息,本文不做身份驗(yàn)證 // String username = data.getSingleUrlParam("username"); // String password = data.getSingleUrlParam("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、添加消息結(jié)構(gòu)類(lèi)MessageInfo.java
package com.xiaofangtech.sunt.message; public class MessageInfo { //源客戶(hù)端id private String sourceClientId; //目標(biāo)客戶(hù)端id private String targetClientId; //消息類(lèi)型 private String msgType; //消息內(nèi)容 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、添加客戶(hù)端信息,用來(lái)存放客戶(hù)端的sessionid
package com.xiaofangtech.sunt.bean; import java.util.Date; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.constraints.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) { this.connected = connected; } public Long getMostsignbits() { return mostsignbits; } public void setMostsignbits(Long mostsignbits) { this.mostsignbits = 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、添加查詢(xún)數(shù)據(jù)庫(kù)接口ClientInfoRepository.java
package com.xiaofangtech.sunt.repository; import org.springframework.data.repository.CrudRepository; import com.xiaofangtech.sunt.bean.ClientInfo; public interface ClientInfoRepository extends CrudRepository{ ClientInfo findClientByclientid(String clientId); }
7、添加消息處理類(lèi)MessageEventHandler.Java
package com.xiaofangtech.sunt.message; import java.util.Date; import java.util.UUID; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.corundumstudio.socketio.AckRequest; import com.corundumstudio.socketio.SocketIOClient; import com.corundumstudio.socketio.SocketIOServer; import com.corundumstudio.socketio.annotation.OnConnect; import com.corundumstudio.socketio.annotation.OnDisconnect; import com.corundumstudio.socketio.annotation.OnEvent; import com.xiaofangtech.sunt.bean.ClientInfo; import com.xiaofangtech.sunt.repository.ClientInfoRepository; @Component public class MessageEventHandler { private final SocketIOServer server; @Autowired private ClientInfoRepository clientInfoRepository; @Autowired public MessageEventHandler(SocketIOServer server) { this.server = server; } //添加connect事件,當(dāng)客戶(hù)端發(fā)起連接時(shí)調(diào)用,本文中將clientid與sessionid存入數(shù)據(jù)庫(kù) //方便后面發(fā)送消息時(shí)查找到對(duì)應(yīng)的目標(biāo)client, @OnConnect public void onConnect(SocketIOClient client) { String clientId = client.getHandshakeData().getSingleUrlParam("clientid"); ClientInfo clientInfo = clientInfoRepository.findClientByclientid(clientId); if (clientInfo != null) { Date nowTime = new Date(System.currentTimeMillis()); clientInfo.setConnected((short)1); clientInfo.setMostsignbits(client.getSessionId().getMostSignificantBits()); clientInfo.setLeastsignbits(client.getSessionId().getLeastSignificantBits()); clientInfo.setLastconnecteddate(nowTime); clientInfoRepository.save(clientInfo); } } //添加@OnDisconnect事件,客戶(hù)端斷開(kāi)連接時(shí)調(diào)用,刷新客戶(hù)端信息 @OnDisconnect public void onDisconnect(SocketIOClient client) { String clientId = client.getHandshakeData().getSingleUrlParam("clientid"); ClientInfo clientInfo = clientInfoRepository.findClientByclientid(clientId); if (clientInfo != null) { clientInfo.setConnected((short)0); clientInfo.setMostsignbits(null); clientInfo.setLeastsignbits(null); clientInfoRepository.save(clientInfo); } } //消息接收入口,當(dāng)接收到消息后,查找發(fā)送目標(biāo)客戶(hù)端,并且向該客戶(hù)端發(fā)送消息,且給自己發(fā)送消息 @OnEvent(value = "messageevent") public void onEvent(SocketIOClient client, AckRequest request, MessageInfo data) { String targetClientId = data.getTargetClientId(); ClientInfo clientInfo = clientInfoRepository.findClientByclientid(targetClientId); if (clientInfo != null && clientInfo.getConnected() != 0) { UUID uuid = new UUID(clientInfo.getMostsignbits(), clientInfo.getLeastsignbits()); System.out.println(uuid.toString()); MessageInfo sendData = new MessageInfo(); sendData.setSourceClientId(data.getSourceClientId()); sendData.setTargetClientId(data.getTargetClientId()); sendData.setMsgType("chat"); sendData.setMsgContent(data.getMsgContent()); client.sendEvent("messageevent", sendData); server.getClient(uuid).sendEvent("messageevent", sendData); } } }
8、添加ServerRunner.java
package com.xiaofangtech.sunt.message; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; import com.corundumstudio.socketio.SocketIOServer; @Component public class ServerRunner implements CommandLineRunner { private final SocketIOServer server; @Autowired public ServerRunner(SocketIOServer server) { this.server = server; } @Override public void run(String... args) throws Exception { server.start(); } }
9、工程結(jié)構(gòu)
10、運(yùn)行測(cè)試
1) 添加基礎(chǔ)數(shù)據(jù),數(shù)據(jù)庫(kù)中預(yù)置3個(gè)客戶(hù)端testclient1,testclient2,testclient3
2) 創(chuàng)建客戶(hù)端文件index.html,index2.html,index3.html分別代表testclient1 testclient2 testclient3三個(gè)用戶(hù)
本文直接修改的https://github.com/mrniko/netty-socketio-demo/tree/master/client 中的index.html文件
其中clientid為發(fā)送者id, targetclientid為目標(biāo)方id,本文簡(jiǎn)單的將發(fā)送方和接收方寫(xiě)死在html文件中
使用 以下代碼進(jìn)行連接
io.connect('http://localhost:8081?clientid='+clientid);
index.html 文件內(nèi)容如下
Demo Chat Netty-socketio Demo Chat
3、本例測(cè)試時(shí)
testclient1 發(fā)送消息給 testclient2
testclient2 發(fā)送消息給 testclient1
testclient3發(fā)送消息給testclient1
運(yùn)行結(jié)果如下
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。