TCPServer 服务
1、首先创建子类实现ServerChannelRead 接口,且实现方法tackle,在tackle 方法中编写自己的业务代码
2、只能在子类注入model接口,在其他地方注入容易造成数据链接丢失问题。
package dynamic;
import dynamic.model.Pimsi_Analysis;
import io.netty.channel.ChannelHandler;
import microbee.http.annotation.ModelResources;
import microbee.http.utills.nettool.ServerChannelRead;import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;@ChannelHandler.Sharable
public class TCPServerTest implements ServerChannelRead {@ModelResources
Pimsi_Analysis pimsi_analysis;@Override
public String tackle(String msg) {
System.out.println("接收到数据=========:"+msg);
synZ(msg);
return "ok";
}private void synZ(String msg) {
// 逻辑实现
msg.getBytes(StandardCharsets.UTF_8);
List<Map<String, Object>> mapList = pimsi_analysis.selectAll(new HashMap<>());
}
}
3、方法使用
package dynamic;
import dynamic.tcp.TCPServer;
import microbee.http.annotation.Controller;
import microbee.http.apps.dynamic.HoContext;import java.util.Map;
@Controller
public class Test1 {
/**
* 开启tcpserver服务
* @param hoContext
* @return
*/
public String start(HoContext hoContext) {
TCPServerTest tcpServerTest = new TCPServerTest();
TCPServer.getInstance().start(Integer.parseInt(hoContext.httpRequest.getParams().get("port")), tcpServerTest);
return "ok";
}/**
* 停止tcpserver服务
* @param hoContext
* @return
*/
public String stop(HoContext hoContext) {
TCPServer.getInstance().stop(Integer.parseInt(hoContext.httpRequest.getParams().get("port")));
return "ok";
}/**
* 发送tcp数据
* @param hoContext
* @return
*/
public String send(HoContext hoContext) {
// 接收参数
Map<String, String> params = hoContext.httpRequest.getParams();
// 端口
int port = Integer.parseInt(params.get("port"));
// 数据
String data = params.get("data");
// session id
String id = params.get("sessionId");
TCPServer.getInstance().sendToSession(port, id, data);
return "ok";
}/**
* 关闭所有tcp服务
* @param hoContext
* @return
*/
public String stopAll(HoContext hoContext) {
TCPServer.getInstance().shutdown();
return "ok";
}
}
如上所示:
1)开启TCPserver:TCPServer为单例模式 调用start方法需要传入端口号以及实现SercerChannelRead的子类。
2)关闭TCPserver: TCPServer为单例模式 调用stop方法只需要传入端口号程序会根据端口号停止该server (停止进程时候果有client正在通讯中则不会断掉该进程,同时其他的client将链接不到高端口server)
3)发送消息TCPserver: TCPServer为单例模式 调用sendToJson方法可根据端口号,sessionid将消息发送至clientd端。
4)停止所有TCPServer: TCPServer为单例模式 调用shutdown方法可停止所有正在运行的TCPServer。
扫一扫