Skip to content
Toggle navigation
Projects
Groups
Snippets
Help
eshiled-new
/
ne-shield-notifycenter
This project
Loading...
Sign in
Toggle navigation
Go to a project
Project
Repository
Issues
0
Merge Requests
0
Pipelines
Wiki
Settings
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Commit 45f8f015
authored
Aug 04, 2022
by
levphon
Browse Files
Options
Browse Files
Tag
Download
Email Patches
Plain Diff
集成netty,支持websocket
1 parent
178e8fbe
Show whitespace changes
Inline
Side-by-side
Showing
20 changed files
with
460 additions
and
167 deletions
pom.xml
src/main/java/cn/com/glsx/Application.java
src/main/java/cn/com/glsx/notify/config/WebConfig.java
src/main/java/cn/com/glsx/notify/config/WebSocketConfig.java
src/main/java/cn/com/glsx/notify/modules/controller/WebSocketServer.java
src/main/java/cn/com/glsx/notify/modules/kafka/MessageConsumer.java
src/main/java/cn/com/glsx/notify/modules/service/PCService.java
src/main/java/cn/com/glsx/notify/modules/websocket/handler/MessageHandler.java
src/main/java/cn/com/glsx/notify/modules/websocket/handler/PersistenceToDatabaseWebSocketHandlerDecorator.java
src/main/java/cn/com/glsx/notify/modules/websocket/handler/PersistenceToElasticsearchWebSocketHandlerDecorator.java
src/main/java/cn/com/glsx/notify/modules/websocket/handler/SessionManager.java
src/main/java/cn/com/glsx/notify/modules/websocket/handler/TextHandler.java
src/main/java/cn/com/glsx/notify/modules/websocket/interceptor/RbacHandshakeInterceptor.java
src/main/java/cn/com/glsx/notify/netty/NettyServer.java → src/main/java/cn/com/glsx/notify/netty/CoordinationNettyServer.java
src/main/java/cn/com/glsx/notify/netty/MyByteEncoder.java
src/main/java/cn/com/glsx/notify/netty/NettyDataSvervice.java → src/main/java/cn/com/glsx/notify/netty/NettyDataService.java
src/main/java/cn/com/glsx/notify/netty/NettyInitializer.java
src/main/java/cn/com/glsx/notify/netty/NettySendThread.java
src/main/java/cn/com/glsx/notify/netty/NettyServerHandler.java
src/main/java/cn/com/glsx/notify/netty/utils/NettyByteAndStringUtils.java
pom.xml
View file @
45f8f01
...
@@ -41,6 +41,10 @@
...
@@ -41,6 +41,10 @@
<groupId>
com.glsx
</groupId>
<groupId>
com.glsx
</groupId>
<artifactId>
rest-admin-im
</artifactId>
<artifactId>
rest-admin-im
</artifactId>
</dependency>
</dependency>
<dependency>
<groupId>
com.glsx
</groupId>
<artifactId>
rest-admin-swagger2
</artifactId>
</dependency>
<dependency>
<dependency>
<groupId>
com.glsx
</groupId>
<groupId>
com.glsx
</groupId>
...
...
src/main/java/cn/com/glsx/Application.java
View file @
45f8f01
package
cn
.
com
.
glsx
;
package
cn
.
com
.
glsx
;
import
cn.com.glsx.notify.netty.CoordinationNettyServer
;
import
com.glsx.plat.context.EnableRestAdmin
;
import
com.glsx.plat.context.EnableRestAdmin
;
import
org.springframework.boot.SpringApplication
;
import
org.springframework.boot.SpringApplication
;
import
org.springframework.boot.autoconfigure.SpringBootApplication
;
import
org.springframework.boot.autoconfigure.SpringBootApplication
;
...
@@ -7,7 +8,9 @@ import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
...
@@ -7,7 +8,9 @@ import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import
org.springframework.cloud.openfeign.EnableFeignClients
;
import
org.springframework.cloud.openfeign.EnableFeignClients
;
import
org.springframework.context.annotation.EnableMBeanExport
;
import
org.springframework.context.annotation.EnableMBeanExport
;
import
org.springframework.jmx.support.RegistrationPolicy
;
import
org.springframework.jmx.support.RegistrationPolicy
;
import
org.springframework.scheduling.annotation.EnableAsync
;
import
org.springframework.transaction.annotation.EnableTransactionManagement
;
import
org.springframework.transaction.annotation.EnableTransactionManagement
;
import
org.springframework.web.socket.config.annotation.EnableWebSocket
;
import
javax.annotation.PostConstruct
;
import
javax.annotation.PostConstruct
;
import
java.util.TimeZone
;
import
java.util.TimeZone
;
...
@@ -18,6 +21,8 @@ import static java.util.TimeZone.getTimeZone;
...
@@ -18,6 +21,8 @@ import static java.util.TimeZone.getTimeZone;
/**
/**
* @author payu
* @author payu
*/
*/
@EnableAsync
@EnableWebSocket
@EnableRestAdmin
@EnableRestAdmin
@EnableDiscoveryClient
@EnableDiscoveryClient
@EnableFeignClients
(
basePackages
=
{
"cn.com.glsx.*.api"
})
@EnableFeignClients
(
basePackages
=
{
"cn.com.glsx.*.api"
})
...
@@ -30,8 +35,7 @@ public class Application {
...
@@ -30,8 +35,7 @@ public class Application {
SpringApplication
.
run
(
Application
.
class
,
args
);
SpringApplication
.
run
(
Application
.
class
,
args
);
//启动NettyServer服务端
//启动NettyServer服务端
// NettyServer nettyServer = new NettyServer();
new
CoordinationNettyServer
(
9779
).
start
();
// nettyServer.run();
}
}
@PostConstruct
@PostConstruct
...
...
src/main/java/cn/com/glsx/notify/config/WebConfig.java
0 → 100644
View file @
45f8f01
package
cn
.
com
.
glsx
.
notify
.
config
;
import
org.springframework.context.annotation.Configuration
;
import
org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry
;
import
org.springframework.web.servlet.config.annotation.WebMvcConfigurer
;
/**
* @author payu
*/
@Configuration
public
class
WebConfig
implements
WebMvcConfigurer
{
@Override
public
void
addResourceHandlers
(
ResourceHandlerRegistry
registry
)
{
registry
.
addResourceHandler
(
"swagger-ui.html"
).
addResourceLocations
(
"classpath:/META-INF/resources/"
);
registry
.
addResourceHandler
(
"/webjars/**"
).
addResourceLocations
(
"classpath:/META-INF/resources/webjars/"
);
}
}
\ No newline at end of file
\ No newline at end of file
src/main/java/cn/com/glsx/notify/config/WebSocketConfig.java
View file @
45f8f01
package
cn
.
com
.
glsx
.
notify
.
config
;
//package cn.com.glsx.notify.config;
//
import
org.springframework.context.annotation.Bean
;
//import cn.com.glsx.notify.modules.websocket.handler.MessageHandler;
import
org.springframework.context.annotation.Configuration
;
//import cn.com.glsx.notify.modules.websocket.handler.PersistenceToDatabaseWebSocketHandlerDecorator;
import
org.springframework.web.socket.server.standard.ServerEndpointExporter
;
//import cn.com.glsx.notify.modules.websocket.handler.PersistenceToElasticsearchWebSocketHandlerDecorator;
//import cn.com.glsx.notify.modules.websocket.handler.TextHandler;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.web.socket.WebSocketHandler;
//import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
//import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
//import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;
//
//@Configuration
//@Configuration
public
class
WebSocketConfig
{
//public class WebSocketConfig implements WebSocketConfigurer {
//
// @Override
// public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
// registry.addHandler(buildMessageHandler(), "/ws/asset")
// //复制HttpSession中的属性到WebSocketSession中
//// .addInterceptors(new RbacHandshakeInterceptor())
// .addInterceptors(new HttpSessionHandshakeInterceptor())
// .setAllowedOrigins("*");
// }
//
// @Bean
// @Bean
public
ServerEndpointExporter
serverEndpointExporter
()
{
return
new
ServerEndpointExporter
();
}
}
\ No newline at end of file
\ No newline at end of file
// public WebSocketHandler buildTextHandler() {
// return new TextHandler();
// }
//
// @Bean
// public WebSocketHandler buildMessageHandler() {
// return new PersistenceToElasticsearchWebSocketHandlerDecorator(new PersistenceToDatabaseWebSocketHandlerDecorator(new MessageHandler()));
// }
//
//}
\ No newline at end of file
\ No newline at end of file
src/main/java/cn/com/glsx/notify/modules/controller/WebSocketServer.java
View file @
45f8f01
/*
package
cn
.
com
.
glsx
.
notify
.
modules
.
controller
;
package
cn
.
com
.
glsx
.
notify
.
modules
.
controller
;
import
lombok.EqualsAndHashCode
;
import
lombok.EqualsAndHashCode
;
...
@@ -15,12 +14,12 @@ import java.util.concurrent.atomic.AtomicInteger;
...
@@ -15,12 +14,12 @@ import java.util.concurrent.atomic.AtomicInteger;
@Slf4j
@Slf4j
@Component
@Component
@EqualsAndHashCode
@EqualsAndHashCode
@ServerEndpoint(value = "/ws
/asset
")
@ServerEndpoint
(
value
=
"/ws"
)
public
class
WebSocketServer
{
public
class
WebSocketServer
{
@PostConstruct
@PostConstruct
public
void
init
()
{
public
void
init
()
{
log.info("
webs
ocket 加载");
log
.
info
(
"
WebS
ocket 加载"
);
}
}
private
Session
session
;
private
Session
session
;
...
@@ -31,11 +30,9 @@ public class WebSocketServer {
...
@@ -31,11 +30,9 @@ public class WebSocketServer {
// concurrent包的线程安全Set,用来存放每个客户端对应的Session对象。
// concurrent包的线程安全Set,用来存放每个客户端对应的Session对象。
private
static
CopyOnWriteArraySet
<
Session
>
SessionSet
=
new
CopyOnWriteArraySet
<>();
private
static
CopyOnWriteArraySet
<
Session
>
SessionSet
=
new
CopyOnWriteArraySet
<>();
*/
/**
/**
* 连接建立成功调用的方法
* 连接建立成功调用的方法
*//*
*/
@OnOpen
@OnOpen
public
void
onOpen
(
Session
session
)
{
public
void
onOpen
(
Session
session
)
{
SessionSet
.
add
(
session
);
SessionSet
.
add
(
session
);
...
@@ -50,11 +47,9 @@ public class WebSocketServer {
...
@@ -50,11 +47,9 @@ public class WebSocketServer {
SendMessage
(
session
,
"连接成功"
);
SendMessage
(
session
,
"连接成功"
);
}
}
*/
/**
/**
* 连接关闭调用的方法
* 连接关闭调用的方法
*//*
*/
@OnClose
@OnClose
public
void
onClose
(
Session
session
)
{
public
void
onClose
(
Session
session
)
{
SessionSet
.
remove
(
session
);
SessionSet
.
remove
(
session
);
...
@@ -64,41 +59,35 @@ public class WebSocketServer {
...
@@ -64,41 +59,35 @@ public class WebSocketServer {
log
.
info
(
"有连接关闭,当前连接数为:{}"
,
cnt
);
log
.
info
(
"有连接关闭,当前连接数为:{}"
,
cnt
);
}
}
*/
/**
/**
* 收到客户端消息后调用的方法
* 收到客户端消息后调用的方法
*
*
* @param message 客户端发送过来的消息
* @param message 客户端发送过来的消息
*//*
*/
@OnMessage
@OnMessage
public
void
onMessage
(
String
message
,
Session
session
)
{
public
void
onMessage
(
String
message
,
Session
session
)
{
log
.
info
(
"来自客户端的消息:{}"
,
message
);
log
.
info
(
"来自客户端的消息:{}"
,
message
);
SendMessage
(
session
,
"收到消息,消息内容:"
+
message
);
SendMessage
(
session
,
"收到消息,消息内容:"
+
message
);
}
}
*/
/**
/**
* 出现错误
* 出现错误
*
*
* @param session
* @param session
* @param error
* @param error
*//*
*/
@OnError
@OnError
public
void
onError
(
Session
session
,
Throwable
error
)
{
public
void
onError
(
Session
session
,
Throwable
error
)
{
log
.
error
(
"发生错误:{},Session ID: {}"
,
error
.
getMessage
(),
session
.
getId
());
log
.
error
(
"发生错误:{},Session ID: {}"
,
error
.
getMessage
(),
session
.
getId
());
error
.
printStackTrace
();
error
.
printStackTrace
();
}
}
*/
/**
/**
* 发送消息,实践表明,每次浏览器刷新,session会发生变化。
* 发送消息,实践表明,每次浏览器刷新,session会发生变化。
*
*
* @param session
* @param session
* @param message
* @param message
*//*
*/
public
static
void
SendMessage
(
Session
session
,
String
message
)
{
public
static
void
SendMessage
(
Session
session
,
String
message
)
{
try
{
try
{
session
.
getBasicRemote
().
sendText
(
message
);
session
.
getBasicRemote
().
sendText
(
message
);
...
@@ -108,14 +97,12 @@ public class WebSocketServer {
...
@@ -108,14 +97,12 @@ public class WebSocketServer {
}
}
}
}
*/
/**
/**
* 群发消息
* 群发消息
*
*
* @param message
* @param message
* @throws IOException
* @throws IOException
*//*
*/
public
static
void
BroadCastInfo
(
String
message
)
throws
IOException
{
public
static
void
BroadCastInfo
(
String
message
)
throws
IOException
{
for
(
Session
session
:
SessionSet
)
{
for
(
Session
session
:
SessionSet
)
{
if
(
session
.
isOpen
())
{
if
(
session
.
isOpen
())
{
...
@@ -124,15 +111,13 @@ public class WebSocketServer {
...
@@ -124,15 +111,13 @@ public class WebSocketServer {
}
}
}
}
*/
/**
/**
* 指定Session发送消息
* 指定Session发送消息
*
*
* @param sessionId
* @param sessionId
* @param message
* @param message
* @throws IOException
* @throws IOException
*//*
*/
public
static
void
SendMessage
(
String
message
,
String
sessionId
)
throws
IOException
{
public
static
void
SendMessage
(
String
message
,
String
sessionId
)
throws
IOException
{
Session
session
=
null
;
Session
session
=
null
;
for
(
Session
s
:
SessionSet
)
{
for
(
Session
s
:
SessionSet
)
{
...
@@ -152,4 +137,3 @@ public class WebSocketServer {
...
@@ -152,4 +137,3 @@ public class WebSocketServer {
this
.
session
.
getBasicRemote
().
sendText
(
message
);
this
.
session
.
getBasicRemote
().
sendText
(
message
);
}
}
}
}
*/
src/main/java/cn/com/glsx/notify/modules/kafka/MessageConsumer.java
View file @
45f8f01
/*
package
cn
.
com
.
glsx
.
notify
.
modules
.
kafka
;
package
cn
.
com
.
glsx
.
notify
.
modules
.
kafka
;
import
cn.com.glsx.notify.modules.controller.WebSocketServer
;
import
cn.com.glsx.notify.modules.controller.WebSocketServer
;
...
@@ -12,17 +11,15 @@ import java.util.Optional;
...
@@ -12,17 +11,15 @@ import java.util.Optional;
import
static
cn
.
com
.
glsx
.
notify
.
modules
.
controller
.
WebSocketServer
.
SocketSet
;
import
static
cn
.
com
.
glsx
.
notify
.
modules
.
controller
.
WebSocketServer
.
SocketSet
;
*/
/**
/**
* @author payu
* @author payu
*//*
*/
@Slf4j
@Slf4j
@Component
@Component
public
class
MessageConsumer
{
public
class
MessageConsumer
{
@KafkaListener(id = "messageConsumer",
@KafkaListener
(
id
=
"messageConsumer"
,
topics
=
"#{'${topic.message.application}'.split(',')}"
,
topics = "#{'${topic.message.application}'.split(',')}",
errorHandler
=
"consumerAwareErrorHandler"
)
errorHandler
=
"consumerAwareErrorHandler"
)
public
void
listener
(
ConsumerRecord
<?,
?>
record
)
{
public
void
listener
(
ConsumerRecord
<?,
?>
record
)
{
//errorHandler异常处理器注解里面使用的也是bean的名称
//errorHandler异常处理器注解里面使用的也是bean的名称
...
@@ -45,4 +42,3 @@ public class MessageConsumer {
...
@@ -45,4 +42,3 @@ public class MessageConsumer {
}
}
}
}
*/
src/main/java/cn/com/glsx/notify/modules/service/PCService.java
View file @
45f8f01
/*
package
cn
.
com
.
glsx
.
notify
.
modules
.
service
;
package
cn
.
com
.
glsx
.
notify
.
modules
.
service
;
import cn.com.glsx.notify.dto.PCTemplateMessageDTO;
import
cn.com.glsx.notify.modules.model.PCTemplateMessageDTO
;
import
com.alibaba.fastjson.JSONObject
;
import
com.alibaba.fastjson.JSONObject
;
import
lombok.extern.slf4j.Slf4j
;
import
lombok.extern.slf4j.Slf4j
;
import
org.springframework.kafka.core.KafkaTemplate
;
import
org.springframework.kafka.core.KafkaTemplate
;
...
@@ -12,11 +12,10 @@ import org.springframework.util.concurrent.ListenableFutureCallback;
...
@@ -12,11 +12,10 @@ import org.springframework.util.concurrent.ListenableFutureCallback;
import
javax.annotation.Resource
;
import
javax.annotation.Resource
;
*/
/**
/**
* @author payu
* @author payu
*//*
*/
@Slf4j
@Slf4j
@Service
@Service
public
class
PCService
{
public
class
PCService
{
...
@@ -45,4 +44,4 @@ public class PCService {
...
@@ -45,4 +44,4 @@ public class PCService {
}
}
}
}
*/
src/main/java/cn/com/glsx/notify/modules/websocket/handler/MessageHandler.java
0 → 100644
View file @
45f8f01
package
cn
.
com
.
glsx
.
notify
.
modules
.
websocket
.
handler
;
import
lombok.extern.slf4j.Slf4j
;
import
org.springframework.web.socket.*
;
import
org.springframework.web.socket.handler.AbstractWebSocketHandler
;
@Slf4j
public
class
MessageHandler
extends
AbstractWebSocketHandler
{
@Override
public
void
afterConnectionEstablished
(
WebSocketSession
session
)
throws
Exception
{
super
.
afterConnectionEstablished
(
session
);
SessionManager
.
put
(
session
.
getId
(),
session
);
log
.
info
(
"session[{}] afterConnectionEstablished"
,
session
.
getId
());
log
.
info
(
"get WebSocketSession attributes={}"
,
session
.
getAttributes
());
}
@Override
public
void
afterConnectionClosed
(
WebSocketSession
session
,
CloseStatus
status
)
throws
Exception
{
log
.
info
(
"session[{}] afterConnectionClosed"
,
session
.
getId
());
SessionManager
.
remove
(
session
.
getId
());
}
@Override
protected
void
handleTextMessage
(
WebSocketSession
session
,
TextMessage
message
)
throws
Exception
{
log
.
info
(
"session[{}] receive text message={}"
,
session
.
getId
(),
message
);
//for test error
if
(
message
.
getPayload
().
equals
(
"error"
)){
throw
new
RuntimeException
(
this
.
getClass
().
getSimpleName
()+
".handleTextMessage error"
);
}
}
@Override
protected
void
handleBinaryMessage
(
WebSocketSession
session
,
BinaryMessage
message
)
throws
Exception
{
log
.
info
(
"session[{}] receive binary message={} length={}"
,
session
.
getId
(),
message
,
message
.
getPayloadLength
());
}
@Override
protected
void
handlePongMessage
(
WebSocketSession
session
,
PongMessage
message
)
throws
Exception
{
log
.
info
(
"session[{}] receive pong message={}"
,
session
.
getId
(),
message
);
}
@Override
public
void
handleTransportError
(
WebSocketSession
session
,
Throwable
exception
)
throws
Exception
{
}
}
src/main/java/cn/com/glsx/notify/modules/websocket/handler/PersistenceToDatabaseWebSocketHandlerDecorator.java
0 → 100644
View file @
45f8f01
package
cn
.
com
.
glsx
.
notify
.
modules
.
websocket
.
handler
;
import
lombok.extern.slf4j.Slf4j
;
import
org.springframework.web.socket.*
;
import
org.springframework.web.socket.handler.WebSocketHandlerDecorator
;
@Slf4j
public
class
PersistenceToDatabaseWebSocketHandlerDecorator
extends
WebSocketHandlerDecorator
{
public
PersistenceToDatabaseWebSocketHandlerDecorator
(
WebSocketHandler
delegate
)
{
super
(
delegate
);
}
public
void
handleMessage
(
WebSocketSession
session
,
WebSocketMessage
<?>
message
)
{
try
{
this
.
getDelegate
().
handleMessage
(
session
,
message
);
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
}
if
(
message
instanceof
TextMessage
)
{
log
.
debug
(
"save text message[{}] to database"
,
message
.
getPayload
());
//todo 这里可以基于任意的jdbc框架来写库
}
else
if
(
message
instanceof
BinaryMessage
)
{
log
.
debug
(
"save binary message to database"
);
}
}
}
src/main/java/cn/com/glsx/notify/modules/websocket/handler/PersistenceToElasticsearchWebSocketHandlerDecorator.java
0 → 100644
View file @
45f8f01
package
cn
.
com
.
glsx
.
notify
.
modules
.
websocket
.
handler
;
import
lombok.extern.slf4j.Slf4j
;
import
org.springframework.web.socket.*
;
import
org.springframework.web.socket.handler.WebSocketHandlerDecorator
;
@Slf4j
public
class
PersistenceToElasticsearchWebSocketHandlerDecorator
extends
WebSocketHandlerDecorator
{
public
PersistenceToElasticsearchWebSocketHandlerDecorator
(
WebSocketHandler
delegate
)
{
super
(
delegate
);
}
public
void
handleMessage
(
WebSocketSession
session
,
WebSocketMessage
<?>
message
)
{
try
{
this
.
getDelegate
().
handleMessage
(
session
,
message
);
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
}
if
(
message
instanceof
TextMessage
)
{
log
.
debug
(
"save text message[{}] to elasticsearch"
,
message
.
getPayload
());
//todo 这里可以基于任意的elasticsearch框架来写入搜索引擎
}
else
if
(
message
instanceof
BinaryMessage
)
{
log
.
debug
(
"save binary message to elasticsearch"
);
}
}
}
src/main/java/cn/com/glsx/notify/modules/websocket/handler/SessionManager.java
0 → 100644
View file @
45f8f01
package
cn
.
com
.
glsx
.
notify
.
modules
.
websocket
.
handler
;
import
org.springframework.web.socket.WebSocketSession
;
import
java.util.HashMap
;
import
java.util.Map
;
import
java.util.Set
;
public
class
SessionManager
{
private
static
final
Map
<
String
,
WebSocketSession
>
sessions
=
new
HashMap
<>();
private
SessionManager
()
{
}
public
static
WebSocketSession
put
(
String
key
,
WebSocketSession
webSocketSession
)
{
return
sessions
.
put
(
key
,
webSocketSession
);
}
public
static
Set
<
String
>
sessions
()
{
return
sessions
.
keySet
();
}
public
static
WebSocketSession
get
(
String
key
)
{
return
sessions
.
get
(
key
);
}
public
static
WebSocketSession
remove
(
String
key
)
{
return
sessions
.
remove
(
key
);
}
}
src/main/java/cn/com/glsx/notify/modules/websocket/handler/TextHandler.java
0 → 100644
View file @
45f8f01
package
cn
.
com
.
glsx
.
notify
.
modules
.
websocket
.
handler
;
import
lombok.extern.slf4j.Slf4j
;
import
org.springframework.web.socket.CloseStatus
;
import
org.springframework.web.socket.TextMessage
;
import
org.springframework.web.socket.WebSocketSession
;
import
org.springframework.web.socket.handler.TextWebSocketHandler
;
@Slf4j
public
class
TextHandler
extends
TextWebSocketHandler
{
private
static
final
String
HEARTBEAT_PING
=
"PING"
;
private
static
final
String
HEARTBEAT_PONG
=
"PONG"
;
private
static
final
TextMessage
HEARTBEAT_PONG_MESSAGE
=
new
TextMessage
(
HEARTBEAT_PONG
);
@Override
protected
void
handleTextMessage
(
WebSocketSession
session
,
TextMessage
message
)
throws
Exception
{
if
(
session
.
isOpen
())
{
log
.
info
(
"receive websocket message:{} session:{}"
,
message
,
session
.
getId
());
if
(
message
.
getPayload
().
equals
(
HEARTBEAT_PING
))
{
session
.
sendMessage
(
HEARTBEAT_PONG_MESSAGE
);
}
else
{
TextMessage
returnMessage
=
new
TextMessage
(
message
.
getPayload
()
+
" received at server"
);
session
.
sendMessage
(
returnMessage
);
}
}
}
@Override
public
void
afterConnectionEstablished
(
WebSocketSession
session
)
throws
Exception
{
super
.
afterConnectionEstablished
(
session
);
SessionManager
.
put
(
session
.
getId
(),
session
);
log
.
info
(
"session[{}] afterConnectionEstablished"
,
session
.
getId
());
}
@Override
public
void
afterConnectionClosed
(
WebSocketSession
session
,
CloseStatus
status
)
throws
Exception
{
log
.
info
(
"session[{}] afterConnectionClosed"
,
session
.
getId
());
SessionManager
.
remove
(
session
.
getId
());
}
}
src/main/java/cn/com/glsx/notify/modules/websocket/interceptor/RbacHandshakeInterceptor.java
0 → 100644
View file @
45f8f01
package
cn
.
com
.
glsx
.
notify
.
modules
.
websocket
.
interceptor
;
import
lombok.extern.slf4j.Slf4j
;
import
org.springframework.http.HttpStatus
;
import
org.springframework.http.server.ServerHttpRequest
;
import
org.springframework.http.server.ServerHttpResponse
;
import
org.springframework.http.server.ServletServerHttpRequest
;
import
org.springframework.util.StringUtils
;
import
org.springframework.web.socket.WebSocketHandler
;
import
org.springframework.web.socket.server.HandshakeInterceptor
;
import
javax.servlet.http.Cookie
;
import
javax.servlet.http.HttpSession
;
import
java.util.Arrays
;
import
java.util.Map
;
import
java.util.Optional
;
@Slf4j
public
class
RbacHandshakeInterceptor
implements
HandshakeInterceptor
{
@Override
public
boolean
beforeHandshake
(
ServerHttpRequest
serverHttpRequest
,
ServerHttpResponse
serverHttpResponse
,
WebSocketHandler
webSocketHandler
,
Map
<
String
,
Object
>
map
)
throws
Exception
{
log
.
debug
(
"beforeHandshake {} to {} websocket request"
,
serverHttpRequest
.
getMethodValue
(),
serverHttpRequest
.
getURI
());
log
.
debug
(
"serverHttpRequest.getHeaders()={}"
,
serverHttpRequest
.
getHeaders
());
// boolean result = handleByCookie(serverHttpRequest);
boolean
result
=
handleByQueryString
(
serverHttpRequest
);
// boolean result = handleByHttpSession(serverHttpRequest);
if
(!
result
)
{
serverHttpResponse
.
setStatusCode
(
HttpStatus
.
FORBIDDEN
);
}
return
result
;
}
private
boolean
handleByCookie
(
ServerHttpRequest
serverHttpRequest
)
{
if
(
serverHttpRequest
instanceof
ServletServerHttpRequest
)
{
ServletServerHttpRequest
servletServerHttpRequest
=
(
ServletServerHttpRequest
)
serverHttpRequest
;
Cookie
[]
cookies
=
servletServerHttpRequest
.
getServletRequest
().
getCookies
();
Optional
<
Cookie
>
cookie
=
Arrays
.
stream
(
cookies
).
filter
(
c
->
c
.
getName
().
equals
(
"token"
)).
findFirst
();
if
(
cookie
.
isPresent
())
{
String
token
=
cookie
.
get
().
getValue
();
log
.
debug
(
"find token from cookie={}"
,
token
);
//todo parse value
return
true
;
}
else
{
log
.
warn
(
"not found token from cookie"
);
return
false
;
}
}
return
false
;
}
private
boolean
handleByQueryString
(
ServerHttpRequest
serverHttpRequest
)
{
if
(
serverHttpRequest
instanceof
ServletServerHttpRequest
)
{
ServletServerHttpRequest
servletServerHttpRequest
=
(
ServletServerHttpRequest
)
serverHttpRequest
;
String
token
=
servletServerHttpRequest
.
getServletRequest
().
getParameter
(
"token"
);
if
(
StringUtils
.
hasLength
(
token
))
{
log
.
debug
(
"find token from querystring={}"
,
token
);
//todo parse value
return
true
;
}
else
{
log
.
warn
(
"not found token from querystring"
);
return
false
;
}
}
return
false
;
}
private
boolean
handleByHttpSession
(
ServerHttpRequest
serverHttpRequest
)
{
if
(
serverHttpRequest
instanceof
ServletServerHttpRequest
)
{
HttpSession
httpSession
=
((
ServletServerHttpRequest
)
serverHttpRequest
).
getServletRequest
().
getSession
();
if
(
httpSession
.
getAttribute
(
"isLogin"
)
!=
null
&&
(
Boolean
)
(
httpSession
.
getAttribute
(
"isLogin"
)))
{
log
.
debug
(
"check session login success"
);
return
true
;
}
else
{
log
.
debug
(
"check session login fail"
);
return
false
;
}
}
return
false
;
}
@Override
public
void
afterHandshake
(
ServerHttpRequest
serverHttpRequest
,
ServerHttpResponse
serverHttpResponse
,
WebSocketHandler
webSocketHandler
,
Exception
e
)
{
log
.
debug
(
"afterHandshake {}"
,
serverHttpRequest
.
getURI
());
}
}
\ No newline at end of file
\ No newline at end of file
src/main/java/cn/com/glsx/notify/netty/NettyServer.java
→
src/main/java/cn/com/glsx/notify/netty/
Coordination
NettyServer.java
View file @
45f8f01
/*
package
cn
.
com
.
glsx
.
notify
.
netty
;
package
cn
.
com
.
glsx
.
notify
.
netty
;
import
io.netty.bootstrap.ServerBootstrap
;
import
io.netty.bootstrap.ServerBootstrap
;
...
@@ -9,22 +8,20 @@ import io.netty.channel.EventLoopGroup;
...
@@ -9,22 +8,20 @@ import io.netty.channel.EventLoopGroup;
import
io.netty.channel.nio.NioEventLoopGroup
;
import
io.netty.channel.nio.NioEventLoopGroup
;
import
io.netty.channel.socket.nio.NioServerSocketChannel
;
import
io.netty.channel.socket.nio.NioServerSocketChannel
;
import
lombok.extern.slf4j.Slf4j
;
import
lombok.extern.slf4j.Slf4j
;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
@Slf4j
@Slf4j
@Component
public
class
CoordinationNettyServer
{
@Configuration
public class NettyServer {
@Value("${netty.server.port}")
private
final
int
port
;
private Integer port;
public
CoordinationNettyServer
(
int
port
)
{
this
.
port
=
port
;
}
public
void
start
()
throws
Exception
{
final
EventLoopGroup
bossGroup
=
new
NioEventLoopGroup
();
final
EventLoopGroup
bossGroup
=
new
NioEventLoopGroup
();
final
EventLoopGroup
workerGroup
=
new
NioEventLoopGroup
();
final
EventLoopGroup
workerGroup
=
new
NioEventLoopGroup
();
public void run() throws Exception {
//创建BossGroup 和 WorkerGroup
//创建BossGroup 和 WorkerGroup
//说明
//说明
//1. 创建两个线程组 bossGroup 和 workerGroup
//1. 创建两个线程组 bossGroup 和 workerGroup
...
@@ -40,36 +37,36 @@ public class NettyServer {
...
@@ -40,36 +37,36 @@ public class NettyServer {
bootstrap
.
group
(
bossGroup
,
workerGroup
)
bootstrap
.
group
(
bossGroup
,
workerGroup
)
//使用NioSocketChannel 作为服务器的通道实现
//使用NioSocketChannel 作为服务器的通道实现
.
channel
(
NioServerSocketChannel
.
class
)
.
channel
(
NioServerSocketChannel
.
class
)
//
设置线程队列得到连接个数(也可以说是并发数)
//设置线程队列得到连接个数(也可以说是并发数)
.
option
(
ChannelOption
.
SO_BACKLOG
,
2048
)
.
option
(
ChannelOption
.
SO_BACKLOG
,
2048
)
//设置保持活动连接状态
//设置保持活动连接状态
.
childOption
(
ChannelOption
.
SO_KEEPALIVE
,
true
)
.
childOption
(
ChannelOption
.
SO_KEEPALIVE
,
true
)
//.handler(null) // 该 handler对应 bossGroup , childHandler 对应 workerGroup
//绑定监听端口
//.childOption(ChannelOption.TCP_NODELAY,true)//socketchannel的设置,关闭延迟发送
.
localAddress
(
this
.
port
)
//该handler对应bossGroup,childHandler对应workerGroup
//.handler(null)
//socketchannel的设置,关闭延迟发送
//.childOption(ChannelOption.TCP_NODELAY,true)
.
childHandler
(
new
NettyInitializer
());
.
childHandler
(
new
NettyInitializer
());
log
.
info
(
".....NettyServer is ready....."
);
log.info(".....服务器 is ready.....");
//启动服务器(并绑定端口), 生成 ChannelFuture 对象
//绑定一个端口并且同步, 生成了一个 ChannelFuture 对象
ChannelFuture
cf
=
bootstrap
.
bind
().
sync
();
//启动服务器(并绑定端口)
ChannelFuture cf = bootstrap.bind(port).sync();
//给cf 注册监听器,监控我们关心的事件
//给cf 注册监听器,监控我们关心的事件
cf.addListener(new ChannelFutureListener() {
cf
.
addListener
((
ChannelFutureListener
)
future
->
{
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if
(
cf
.
isSuccess
())
{
if
(
cf
.
isSuccess
())
{
log
.
info
(
"监听端口[{}]成功!"
,
port
);
log
.
info
(
"监听端口[{}]成功!"
,
port
);
}
else
{
}
else
{
log
.
error
(
"监听端口[{}]失败!"
,
port
);
log
.
error
(
"监听端口[{}]失败!"
,
port
);
}
}
}
});
});
//对关闭通道进行监听
//对关闭通道进行监听
cf
.
channel
().
closeFuture
().
sync
();
cf
.
channel
().
closeFuture
().
sync
();
}
catch
(
Exception
e
)
{
}
catch
(
Exception
e
)
{
log.error("
netty服务
启动异常 " + e.getMessage());
log
.
error
(
"
NettyServer
启动异常 "
+
e
.
getMessage
());
}
finally
{
}
finally
{
bossGroup
.
shutdownGracefully
();
bossGroup
.
shutdownGracefully
();
workerGroup
.
shutdownGracefully
();
workerGroup
.
shutdownGracefully
();
}
}
}
}
}
*/
}
src/main/java/cn/com/glsx/notify/netty/MyByteEncoder.java
View file @
45f8f01
/*
package
cn
.
com
.
glsx
.
notify
.
netty
;
package
cn
.
com
.
glsx
.
notify
.
netty
;
import
io.netty.buffer.ByteBuf
;
import
io.netty.buffer.ByteBuf
;
...
@@ -18,4 +17,4 @@ public class MyByteEncoder extends MessageToByteEncoder<byte[]> {
...
@@ -18,4 +17,4 @@ public class MyByteEncoder extends MessageToByteEncoder<byte[]> {
//字节数组
//字节数组
out
.
writeBytes
(
bytes
);
out
.
writeBytes
(
bytes
);
}
}
}
*/
}
src/main/java/cn/com/glsx/notify/netty/NettyDataS
v
ervice.java
→
src/main/java/cn/com/glsx/notify/netty/NettyDataService.java
View file @
45f8f01
/*
package
cn
.
com
.
glsx
.
notify
.
netty
;
package
cn
.
com
.
glsx
.
notify
.
netty
;
import
cn.com.glsx.notify.modules.controller.WebSocketServer
;
import
cn.com.glsx.notify.modules.controller.WebSocketServer
;
...
@@ -8,28 +7,26 @@ import java.io.IOException;
...
@@ -8,28 +7,26 @@ import java.io.IOException;
import
java.util.concurrent.locks.ReentrantLock
;
import
java.util.concurrent.locks.ReentrantLock
;
@Slf4j
@Slf4j
public class NettyDataS
v
ervice {
public
class
NettyDataService
{
private
static
final
ReentrantLock
Lock
=
new
ReentrantLock
();
private
static
final
ReentrantLock
Lock
=
new
ReentrantLock
();
*/
/**
/**
* 将传送过来的数据进行解析,包括异或运算 (第一次服务器端给客户端发)
* 将传送过来的数据进行解析,包括异或运算 (第一次服务器端给客户端发)
*
*
* @param receiveData
* @param receiveData
* @return
* @return
*//*
*/
public
static
String
sendData
(
String
receiveData
)
{
public
static
String
sendData
(
String
receiveData
)
{
final
ReentrantLock
putLock
=
Lock
;
final
ReentrantLock
putLock
=
Lock
;
log
.
info
(
"接收数据"
+
receiveData
);
log
.
info
(
"接收数据"
+
receiveData
);
putLock
.
lock
();
putLock
.
lock
();
try
{
try
{
//此处需要读数据进行校验以及分包黏包处理,本文主要提供思路所以省略
//此处需要读数据进行校验以及分包黏包处理,本文主要提供思路所以省略
/*
*处理分包黏包、拆分、解析等
*/
*/
/*
* 处理分包黏包、拆分、解析等
*//*
//数据解析
//数据解析
parseData
(
receiveData
);
parseData
(
receiveData
);
...
@@ -45,13 +42,12 @@ public class NettyDataSvervice {
...
@@ -45,13 +42,12 @@ public class NettyDataSvervice {
}
}
}
}
*/
/**
* 数据入库处理
*//*
/**
* 数据入库处理
*/
public
static
void
parseData
(
String
receiveData
)
{
public
static
void
parseData
(
String
receiveData
)
{
System
.
out
.
println
(
"执行入库操作"
);
System
.
out
.
println
(
"执行入库操作"
);
}
}
}
}
*/
src/main/java/cn/com/glsx/notify/netty/NettyInitializer.java
View file @
45f8f01
/*
package
cn
.
com
.
glsx
.
notify
.
netty
;
package
cn
.
com
.
glsx
.
notify
.
netty
;
import
io.netty.channel.Channel
;
import
io.netty.channel.Channel
;
import
io.netty.channel.ChannelHandler
;
import
io.netty.channel.ChannelHandler
;
import
io.netty.channel.ChannelInitializer
;
import
io.netty.channel.ChannelInitializer
;
import
io.netty.handler.codec.http.HttpObjectAggregator
;
import
io.netty.handler.codec.http.HttpServerCodec
;
import
io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler
;
import
io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler
;
import
io.netty.handler.stream.ChunkedWriteHandler
;
import
lombok.extern.slf4j.Slf4j
;
import
lombok.extern.slf4j.Slf4j
;
import org.springframework.beans.factory.annotation.Autowired;
import
org.springframework.stereotype.Component
;
import
org.springframework.stereotype.Component
;
@Slf4j
@Slf4j
...
@@ -13,9 +16,6 @@ import org.springframework.stereotype.Component;
...
@@ -13,9 +16,6 @@ import org.springframework.stereotype.Component;
@ChannelHandler
.
Sharable
@ChannelHandler
.
Sharable
public
class
NettyInitializer
extends
ChannelInitializer
{
public
class
NettyInitializer
extends
ChannelInitializer
{
@Autowired
public MyByteEncoder myByteEncoder;
@Override
@Override
protected
void
initChannel
(
Channel
channel
)
throws
Exception
{
protected
void
initChannel
(
Channel
channel
)
throws
Exception
{
//创建一个通道初始化对象(匿名对象)
//创建一个通道初始化对象(匿名对象)
...
@@ -27,6 +27,15 @@ public class NettyInitializer extends ChannelInitializer {
...
@@ -27,6 +27,15 @@ public class NettyInitializer extends ChannelInitializer {
//channel.pipeline().addLast(new MyByteToLongDecoder2());
//channel.pipeline().addLast(new MyByteToLongDecoder2());
//出站编码
//出站编码
channel
.
pipeline
().
addLast
(
new
MyByteEncoder
());
channel
.
pipeline
().
addLast
(
new
MyByteEncoder
());
channel.pipeline().addLast(new NettyServerHandler());
//websocket协议本身是基于http协议的,所以这边也要使用http解编码器
channel
.
pipeline
().
addLast
(
new
HttpServerCodec
());
//以块的方式来写的处理器
channel
.
pipeline
().
addLast
(
new
ChunkedWriteHandler
());
channel
.
pipeline
().
addLast
(
new
HttpObjectAggregator
(
1024
*
1024
));
//WebSocket 数据压缩 ,压缩来自 client
channel
.
pipeline
().
addLast
(
new
WebSocketServerCompressionHandler
());
channel
.
pipeline
().
addLast
(
new
WebSocketServerProtocolHandler
(
"/ws"
,
"WebSocket"
,
true
,
65536
*
10
));
channel
.
pipeline
().
addLast
(
new
NettyServerHandler
());
//自定义消息处理类
}
}
}
*/
}
src/main/java/cn/com/glsx/notify/netty/NettySendThread.java
View file @
45f8f01
/*
package
cn
.
com
.
glsx
.
notify
.
netty
;
package
cn
.
com
.
glsx
.
notify
.
netty
;
import
cn.com.glsx.notify.netty.utils.NettyByteAndStringUtils
;
import
cn.com.glsx.notify.netty.utils.NettyByteAndStringUtils
;
import
com.glsx.plat.common.utils.StringUtils
;
import
io.netty.buffer.ByteBuf
;
import
io.netty.channel.ChannelHandlerContext
;
import
io.netty.channel.ChannelHandlerContext
;
import
io.netty.handler.codec.http.websocketx.TextWebSocketFrame
;
import
lombok.extern.slf4j.Slf4j
;
import
lombok.extern.slf4j.Slf4j
;
import
java.time.LocalTime
;
import
java.time.LocalTime
;
import java.util.Objects;
@Slf4j
@Slf4j
public
class
NettySendThread
implements
Runnable
{
public
class
NettySendThread
implements
Runnable
{
private
ChannelHandlerContext
ctx
;
private
ChannelHandlerContext
ctx
;
private
String
data;
private
Object
data
;
public NettySendThread(ChannelHandlerContext ctx,
String
data) {
public
NettySendThread
(
ChannelHandlerContext
ctx
,
Object
data
)
{
this
.
ctx
=
ctx
;
this
.
ctx
=
ctx
;
this
.
data
=
data
;
this
.
data
=
data
;
}
}
@Override
@Override
public
void
run
()
{
public
void
run
()
{
String bcc = NettyDataSvervice.sendData(data);
if
(
data
instanceof
ByteBuf
)
{
log.info("接收需要返回的消息:" + bcc);
//将 msg 转成一个 ByteBuf
if (Objects.isNull(bcc)) {
//ByteBuf 是 Netty 提供的,不是 NIO 的 ByteBuffer.
ByteBuf
buf
=
(
ByteBuf
)
data
;
//得到此时客户端的数据长度
int
bytes_length
=
buf
.
readableBytes
();
//组件新的字节数组
byte
[]
buffer
=
new
byte
[
bytes_length
];
buf
.
readBytes
(
buffer
);
String
allData
=
NettyByteAndStringUtils
.
byteToHex
(
buffer
);
log
.
info
(
"进入服务端数据:"
+
allData
);
String
reply
=
NettyDataService
.
sendData
(
allData
);
log
.
info
(
"接收需要返回的消息:"
+
reply
);
if
(
StringUtils
.
isNullOrEmpty
(
reply
))
{
return
;
return
;
}
}
//数据的发送与接收都是16进制
//数据的发送与接收都是16进制
byte[] sendData = NettyByteAndStringUtils.hexToByte(bcc
);
byte
[]
sendData
=
NettyByteAndStringUtils
.
hexToByte
(
reply
);
log
.
info
(
"发送数据时间: "
+
LocalTime
.
now
());
log
.
info
(
"发送数据时间: "
+
LocalTime
.
now
());
ctx
.
writeAndFlush
(
sendData
);
ctx
.
writeAndFlush
(
sendData
);
}
else
if
(
data
instanceof
TextWebSocketFrame
)
{
TextWebSocketFrame
frame
=
(
TextWebSocketFrame
)
data
;
String
allData
=
frame
.
text
();
log
.
info
(
"进入服务端数据:"
+
allData
);
String
reply
=
null
;
if
(
"你好"
.
equals
(
allData
))
{
reply
=
"你好"
;
}
if
(
"在干吗"
.
equals
(
allData
))
{
reply
=
"学习"
;
}
if
(
StringUtils
.
isNullOrEmpty
(
reply
))
{
return
;
}
TextWebSocketFrame
webSocketFrame
=
new
TextWebSocketFrame
(
reply
);
//写回数据也是按照协议格式写TextWebSocketFrame
ctx
.
writeAndFlush
(
webSocketFrame
);
}
else
{
return
;
}
}
}
}
}
*/
src/main/java/cn/com/glsx/notify/netty/NettyServerHandler.java
View file @
45f8f01
/*
package
cn
.
com
.
glsx
.
notify
.
netty
;
package
cn
.
com
.
glsx
.
notify
.
netty
;
import cn.com.glsx.notify.netty.utils.NettyByteAndStringUtils;
import io.netty.buffer.ByteBuf;
import
io.netty.channel.*
;
import
io.netty.channel.*
;
import
io.netty.handler.timeout.IdleState
;
import
io.netty.handler.timeout.IdleState
;
import
io.netty.handler.timeout.IdleStateEvent
;
import
io.netty.handler.timeout.IdleStateEvent
;
...
@@ -26,11 +23,9 @@ public class NettyServerHandler extends ChannelInboundHandlerAdapter {
...
@@ -26,11 +23,9 @@ public class NettyServerHandler extends ChannelInboundHandlerAdapter {
private
static
Lock
lock_4
=
new
ReentrantLock
();
private
static
Lock
lock_4
=
new
ReentrantLock
();
*/
/**
/**
* 管理一个全局map,保存连接进服务端的通道数量
* 管理一个全局map,保存连接进服务端的通道数量
*//*
*/
private
static
final
ConcurrentHashMap
<
ChannelId
,
ChannelHandlerContext
>
CHANNEL_MAP
=
new
ConcurrentHashMap
<>();
private
static
final
ConcurrentHashMap
<
ChannelId
,
ChannelHandlerContext
>
CHANNEL_MAP
=
new
ConcurrentHashMap
<>();
@Override
//数据读取完毕
@Override
//数据读取完毕
...
@@ -41,29 +36,25 @@ public class NettyServerHandler extends ChannelInboundHandlerAdapter {
...
@@ -41,29 +36,25 @@ public class NettyServerHandler extends ChannelInboundHandlerAdapter {
//ctx.writeAndFlush(Unpooled.copiedBuffer("hello, 客户端~(>^ω^<)喵1", CharsetUtil.UTF_8));
//ctx.writeAndFlush(Unpooled.copiedBuffer("hello, 客户端~(>^ω^<)喵1", CharsetUtil.UTF_8));
}
}
*/
/**
/**
* 处理异常, 一般是需要关闭通道
* 处理异常, 一般是需要关闭通道
*
*
* @param ctx
* @param ctx
* @param cause
* @param cause
* @throws Exception
* @throws Exception
*//*
*/
@Override
@Override
public
void
exceptionCaught
(
ChannelHandlerContext
ctx
,
Throwable
cause
)
throws
Exception
{
public
void
exceptionCaught
(
ChannelHandlerContext
ctx
,
Throwable
cause
)
throws
Exception
{
ctx
.
close
();
ctx
.
close
();
log.info("服务端
异常关闭" + ctx.channel
());
log
.
info
(
"服务端
{}异常关闭,异常信息:{}"
,
ctx
.
channel
(),
cause
.
getMessage
());
}
}
*/
/**
/**
* @param ctx
* @param ctx
* @DESCRIPTION: 有客户端连接服务器会触发此函数
* @DESCRIPTION: 有客户端连接服务器会触发此函数
* @return: void
* @return: void
*//*
*/
@Override
@Override
public
void
channelActive
(
ChannelHandlerContext
ctx
)
throws
Exception
{
public
void
channelActive
(
ChannelHandlerContext
ctx
)
throws
Exception
{
lock_1
.
lock
();
lock_1
.
lock
();
...
@@ -85,13 +76,11 @@ public class NettyServerHandler extends ChannelInboundHandlerAdapter {
...
@@ -85,13 +76,11 @@ public class NettyServerHandler extends ChannelInboundHandlerAdapter {
}
}
}
}
*/
/**
/**
* @param ctx
* @param ctx
* @DESCRIPTION: 有客户端终止连接服务器会触发此函数
* @DESCRIPTION: 有客户端终止连接服务器会触发此函数
* @return: void
* @return: void
*//*
*/
@Override
@Override
public
void
channelInactive
(
ChannelHandlerContext
ctx
)
throws
Exception
{
public
void
channelInactive
(
ChannelHandlerContext
ctx
)
throws
Exception
{
lock_2
.
lock
();
lock_2
.
lock
();
...
@@ -110,40 +99,25 @@ public class NettyServerHandler extends ChannelInboundHandlerAdapter {
...
@@ -110,40 +99,25 @@ public class NettyServerHandler extends ChannelInboundHandlerAdapter {
}
}
}
}
/**
*/
/**
* 1. ChannelHandlerContext ctx:上下文对象, 含有 管道pipeline , 通道channel, 地址
* 1. ChannelHandlerContext ctx:上下文对象, 含有 管道pipeline , 通道channel, 地址
* 2. Object msg: 就是客户端发送的数据 默认Object
* 2. Object msg: 就是客户端发送的数据 默认Object
* <p>
* <p>
* 读取数据实际(这里我们可以读取客户端发送的消息)
* 读取数据实际(这里我们可以读取客户端发送的消息)
*/
/*
*/
@Override
@Override
public
void
channelRead
(
ChannelHandlerContext
ctx
,
Object
msg
)
throws
Exception
{
public
void
channelRead
(
ChannelHandlerContext
ctx
,
Object
msg
)
throws
Exception
{
lock_3
.
lock
();
lock_3
.
lock
();
try
{
try
{
log.info("服务器读取线程 " + Thread.currentThread().getName() + " channle = " + ctx.channel());
Channel
channel
=
ctx
.
channel
();
Channel
channel
=
ctx
.
channel
();
//将 msg 转成一个 ByteBuf
log
.
info
(
"服务器读取线程 "
+
Thread
.
currentThread
().
getName
()
+
" channel = "
+
channel
.
toString
());
//ByteBuf 是 Netty 提供的,不是 NIO 的 ByteBuffer.
ctx
.
executor
().
execute
(
new
NettySendThread
(
ctx
,
msg
));
ByteBuf buf = (ByteBuf) msg;
//得到此时客户端的数据长度
int bytes_length = buf.readableBytes();
//组件新的字节数组
byte[] buffer = new byte[bytes_length];
buf.readBytes(buffer);
final String allData = NettyByteAndStringUtils.byteToHex(buffer);
log.info("进入服务端数据:" + allData);
ctx.executor().execute(new NettySendThread(ctx, allData));
}
finally
{
}
finally
{
lock_3
.
unlock
();
lock_3
.
unlock
();
}
}
}
}
@Override
@Override
public
void
userEventTriggered
(
ChannelHandlerContext
ctx
,
Object
evt
)
throws
Exception
{
public
void
userEventTriggered
(
ChannelHandlerContext
ctx
,
Object
evt
)
throws
Exception
{
lock_4
.
lock
();
lock_4
.
lock
();
...
@@ -166,4 +140,4 @@ public class NettyServerHandler extends ChannelInboundHandlerAdapter {
...
@@ -166,4 +140,4 @@ public class NettyServerHandler extends ChannelInboundHandlerAdapter {
lock_4
.
unlock
();
lock_4
.
unlock
();
}
}
}
}
}
*/
}
src/main/java/cn/com/glsx/notify/netty/utils/NettyByteAndStringUtils.java
View file @
45f8f01
/*
package
cn
.
com
.
glsx
.
notify
.
netty
.
utils
;
package
cn
.
com
.
glsx
.
notify
.
netty
.
utils
;
import
java.util.concurrent.locks.ReentrantLock
;
import
java.util.concurrent.locks.ReentrantLock
;
...
@@ -8,11 +7,9 @@ public class NettyByteAndStringUtils {
...
@@ -8,11 +7,9 @@ public class NettyByteAndStringUtils {
private
final
static
ReentrantLock
Lock
=
new
ReentrantLock
();
private
final
static
ReentrantLock
Lock
=
new
ReentrantLock
();
*/
/**
/**
* byte数组转hex
* byte数组转hex
*//*
*/
public
static
String
byteToHex
(
byte
[]
bytes
)
{
public
static
String
byteToHex
(
byte
[]
bytes
)
{
final
ReentrantLock
putLock
=
Lock
;
final
ReentrantLock
putLock
=
Lock
;
putLock
.
lock
();
putLock
.
lock
();
...
@@ -30,11 +27,10 @@ public class NettyByteAndStringUtils {
...
@@ -30,11 +27,10 @@ public class NettyByteAndStringUtils {
}
}
}
}
*/
/**
* hex转byte数组
*//*
/**
* hex转byte数组
*/
public
static
byte
[]
hexToByte
(
String
hex
)
{
public
static
byte
[]
hexToByte
(
String
hex
)
{
final
ReentrantLock
putLock
=
Lock
;
final
ReentrantLock
putLock
=
Lock
;
putLock
.
lock
();
putLock
.
lock
();
...
@@ -55,11 +51,10 @@ public class NettyByteAndStringUtils {
...
@@ -55,11 +51,10 @@ public class NettyByteAndStringUtils {
}
}
}
}
*/
/**
* 字节数组的大小
*//*
/**
* 字节数组的大小
*/
public
static
int
getByteSize
(
byte
[]
bytes
)
{
public
static
int
getByteSize
(
byte
[]
bytes
)
{
final
ReentrantLock
putLock
=
Lock
;
final
ReentrantLock
putLock
=
Lock
;
putLock
.
lock
();
putLock
.
lock
();
...
@@ -80,4 +75,3 @@ public class NettyByteAndStringUtils {
...
@@ -80,4 +75,3 @@ public class NettyByteAndStringUtils {
}
}
}
}
}
}
*/
Write
Preview
Markdown
is supported
Attach a file
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to post a comment