javasocketio⼊门教程(⾃制聊天系统)
java socketio ⼊门Demo
WebSocket :⼀种通信协议 ,其作⽤建⽴⼀个连接通道,使数据交互从传统的请求响应的⽅式 改为了实时的双向推送 ,解决了 http 协议的部分不⾜
这⾥就直接整合了spring boot,spring boot 太⾹了
聊天demo代码(服务器版)
1. 依赖(没贴spring boot的)
<dependency>
<groupId&undumstudio.socketio</groupId>
<artifactId>netty-socketio</artifactId>
<version>1.7.11</version>
</dependency>
2. 设置全局的配置对象
@Configuration
public class SocketConfig {
private int PORT =8081;
private String HOST ="localhost";
@Bean
public SocketIOServer socketIOServer(){
//不设置主机、默认绑定0.0.0.0 or ::0
//        config.setHostname(WSS_HOST);
config.setPort(PORT);
//这⾥还可以认证很多设置⽐如仓库什么的
//⾝份验证
config.setAuthorizationListener(handshakeData ->{
//这⾥没有启⽤任何认证直接返回为 true,可以在这⾥写⽤户认证的逻辑
//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);
}
}
3. 编写消息处理者
@Component
public class MessageHandler {
private static final Logger log = Logger(MessageHandler.class);
/
/会话集合,⽤来存储所有的客户端信息
private static final ConcurrentSkipListMap<String, ClientInfo> webSocketMap =new ConcurrentSkipListMap<>();
//静态变量,⽤来记录当前在线连接数。(原⼦类、线程安全)
private static AtomicInteger onlineCount =new AtomicInteger(0);
//服务器全局对象发送信息就靠它了
private final SocketIOServer server;
@Autowired
public MessageHandler(SocketIOServer server){
this.server = server;
}
/**
* connect事件处理,当客户端发起连接时将调⽤,每次建⽴连接都会调⽤⼀次该⽅法
*
* @param client
*/
@OnConnect
public void onConnect(SocketIOClient client){
// clientid 来⾃请求地址中
String clientId = HandshakeData().getSingleUrlParam("clientid");
log.info("web socket连接:"+ clientId);
UUID session = SessionId();
ClientInfo si = (clientId);
/
/ 如果没有连接信息、则新建会话信息
if(si == null){
si =new ClientInfo();
si.setOnline(true);
//在线数加1
log.info("socket 建⽴新连接、sessionId:"+ session +"、clientId:"+ clientId +"、当前连接数:"+ onlineCount.incrementAndGet());
}
// 更新客户端连接信息
si.LeastSignificantBits());
si.MostSignificantBits());
si.setLastConnectedTime(new Date());
//将会话信息更新保存⾄集合中
webSocketMap.put(clientId, si);
}
public void sendMessage(Object Message){
// 这个⽅法会向所有的客户端发送信息。事件名为 message_event
// 只有客户端有监听这个事件就能接收到信息
for(String clientId : webSocketMap.keySet()){
ClientInfo clientInfo = (clientId);
System.out.printf("开始往客户端%s发送数据", clientId);
UUID session =new MostSignificantBits(), LeastSignificantBits());
}
}
/**
* 断开连接
*
* @param client
*/
@OnDisconnect
public void onDisconnect(SocketIOClient client){
String clientId = HandshakeData().getSingleUrlParam("clientid");
/
/在线数减1
log.info("socket 断开连接、sessionId:"+ SessionId()+"、clientId:"+ clientId +"、当前连接数:"+ onlineCount.decrementAndGet());
}
/**
* 消息接收⼊⼝,当接收到消息后,查发送⽬标客户端,并且向该客户端发送消息,且给⾃⼰发送消息    *
* @param client
* @param request
* @param data
*/
// onEvnt 对某个事件进⾏监听当客户端有触发这个事件时候调⽤。这⾥是⼀个聊天的逻辑处理
@OnEvent(value ="message_event")
public void onEvent(SocketIOClient client, AckRequest request, MessageInfo data){
// MessageInfo 该对象由客户端发送事件时候提供
String targetClientId = TargetClientId();
ClientInfo clientInfo = (targetClientId);
//如果⽬标在线那么发送消息,如果不在线就不进⾏处理
if(clientInfo != null && clientInfo.isOnline()){
UUID target =new MostSignificantBits(), LeastSignificantBits());            log.info("⽬标会话UUID:"+ target);
MessageInfo sendData =new MessageInfo();
sendData.SourceClientId());
sendData.TargetClientId());
sendData.Msg());
// 向当前会话发送信息
client.sendEvent("message_event", sendData);
// 向⽬标会话发送信息
}
}
/**
* socket会话信息
* 下⾯是⾃定义的⼀些消息对象
*/
@Data
public class ClientInfo {
private String clientId;
private boolean isOnline;
private long mostSignificantBits;
private long leastSignificantBits;
private Date lastConnectedTime;
}
/**
* 消息对象
*/
public static class MessageInfo {
//源客户端id
private String sourceClientId;
//⽬标客户端id
private String targetClientId;
//消息内容
private String msg;
// get/set⽅法 ....
public void setSourceClientId(String sourceClientId){
this.sourceClientId = sourceClientId;
}
public void setTargetClientId(String targetClientId){
this.targetClientId = targetClientId;
}
}
public void setMsg(String msg){
this.msg = msg;
}
public String getSourceClientId(){
return sourceClientId;
}
public String getTargetClientId(){
return targetClientId;
}
public String getMsg(){
return msg;
}
}
}
客户端代码
客户端1
<!DOCTYPE html>
<html>
<head lang="zh">
<meta charset="utf-8"/>
<meta http-equiv="Content-Type"content="text/html; charset=gb2312">
<title>Demo Chat</title>
<link href="cdn.bootcss/bootstrap/4.0.0-alpha.6/css/bootstrap.css"rel="stylesheet">
<script src="cdnjs.cloudflare/ajax/libs/socket.io/1.7.3/socket.io.js"></script>
<!--moment js下载地址:momentjs/ -->
<script src="moment.js"></script>
<script src="code.jquery/jquery-1.10.1.min.js"></script>
<style>
body{padding: 20px;}#console{height: 400px;overflow: auto;}.username-msg{color: orange;}.connect-msg{color: green;}.disconnect-msg{color: r ed;}.send-msg{color: #888}
</style>
<script>
var clientId ='user1',targetId ='user2';
var socket = io.connect('localhost:8081?clientid='+ clientId);
<('connect',function(){
showMsg('<span class="connect-msg">成功连接到服务器!</span>');
});
<('message_event',function(data){
showMsg('<br /><span class="username-msg">'+new Date().getHours()+' '+new Date().getMinutes()+' '+new Date().getSeconds()+'</span> '+ d ata);
});
<('disconnect',function(){
showMsg('<span class="disconnect-msg">服务已断开!</span>');
});
function sendDisconnect(){
socket.disconnect();
}
function sendMessage(){
jquery在线教程交流
var message =$('#msg').val();
$('#msg').val('');
var jsonObject ={
sourceClientId: clientId,
targetClientId: targetId,
msg: message
};
}
function showMsg(message){
// alert(message)
// var currentTime = "<span class='time'>" + moment().startOf('hour').fromNow() + "</span>";
// var element = $("<div>" + currentTime + "" + message + "</div>");
$('#console').append(message);
}
$(document).keydown(function(e){
if(e.keyCode ==13){
$('#send').click();
}
});
</script>
</head>
<body>
<h1>Netty-socket.io Demo</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>
客户端2

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