TcpServer.java
2.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package com.huaheng.pc.config.sn.tcp;
import com.baomidou.mybatisplus.extension.api.R;
import com.huaheng.common.utils.AddressUtils;
import com.huaheng.framework.web.domain.AjaxResult;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
@Component
@Slf4j
@Data
public class TcpServer implements CommandLineRunner {
@Resource
private AddressUtils addressUtils;
@Override
public void run(String... args) throws Exception {
Integer port =10000;
if(!addressUtils.isAlllowPort()){
port=20000;
}
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) throws Exception {
ChannelPipeline pipeline = channel.pipeline();
pipeline.addLast(new StringEncoder());
pipeline.addLast(new StringDecoder());
pipeline.addLast(new TCPServerHandler());
}
})
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true);
ChannelFuture future = bootstrap.bind(port).sync();
log.info("TCP server started and listening on port " + port);
future.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
public AjaxResult clientList(){
System.out.println(TCPServerHandler.channelGroup);
TCPServerHandler.channelGroup.forEach(ch->{
System.out.println("客户端ip及port:"+ch.remoteAddress());
});
return AjaxResult.success().setData(TCPServerHandler.channelGroup.size());
}
public AjaxResult sendToMsg(String clientIpPort,String sendMsg){
TCPServerHandler.channelGroup.forEach(ch->{
System.out.println("客户端ip及port:"+ch.remoteAddress());
if(clientIpPort.equals(ch.remoteAddress().toString())){
ch.writeAndFlush(sendMsg);
}
});
return AjaxResult.success();
}
}