UDP client

This commit is contained in:
liujiahua123123 2019-08-11 23:31:37 +08:00
parent 48db4a92b7
commit fa4adfd596
4 changed files with 78 additions and 124 deletions

View File

@ -5,6 +5,8 @@ import net.mamoe.mirai.event.MiraiEventManager;
import net.mamoe.mirai.event.events.server.ServerDisableEvent;
import net.mamoe.mirai.event.events.server.ServerEnableEvent;
import net.mamoe.mirai.network.MiraiNetwork;
import net.mamoe.mirai.network.MiraiUDPClient;
import net.mamoe.mirai.network.MiraiUDPServer;
import net.mamoe.mirai.task.MiraiTaskManager;
import net.mamoe.mirai.utils.LoggerTextFormat;
import net.mamoe.mirai.utils.MiraiLogger;
@ -14,6 +16,9 @@ import net.mamoe.mirai.utils.config.MiraiMapSection;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Scanner;
@ -48,7 +53,6 @@ public class MiraiServer {
protected MiraiServer(){
instance = this;
this.onLoad();
Thread.yield();
this.onEnable();
}
@ -84,6 +88,7 @@ public class MiraiServer {
this.setting = new MiraiConfig(setting);
}
/*
MiraiMapSection qqs = this.setting.getMapSection("qq");
qqs.forEach((a,p) -> {
this.getLogger().log(LoggerTextFormat.SKY_BLUE + "Finding available ports between " + "1-65536");
@ -95,6 +100,23 @@ public class MiraiServer {
e.printStackTrace();
}
});
*/
System.out.println("network test");
try {
MiraiUDPServer server = new MiraiUDPServer();
MiraiUDPClient client = new MiraiUDPClient(InetAddress.getLocalHost(),9999,MiraiNetwork.getAvailablePort());
this.getTaskManager().repeatingTask(() -> {
byte[] sendInfo = "test test".getBytes(StandardCharsets.UTF_8);
try {
client.send(new DatagramPacket(sendInfo,sendInfo.length));
} catch (IOException e) {
e.printStackTrace();
}
},300);
} catch (IOException e) {
e.printStackTrace();
}
}
public void initSetting(File setting){

View File

@ -1,5 +1,7 @@
package net.mamoe.mirai.network;
import net.mamoe.mirai.MiraiServer;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.*;
@ -10,6 +12,7 @@ public class MiraiUDPClient {
private Thread thread;
public MiraiUDPClient(InetAddress target, int targetPort, int localPort) {
MiraiServer.getInstance().getLogger().log("creating client");
try{
this.localUDPSocket = new DatagramSocket(localPort);
this.localUDPSocket.connect(target,targetPort);
@ -36,6 +39,7 @@ public class MiraiUDPClient {
} catch (SocketException e) {
e.printStackTrace();
}
MiraiServer.getInstance().getLogger().log("created client");
}
public void onReceive(DatagramPacket packet){
System.out.println(new String(packet.getData(), 0 , packet.getLength(), StandardCharsets.UTF_8));

View File

@ -0,0 +1,51 @@
package net.mamoe.mirai.network;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.handler.codec.dns.DatagramDnsQueryDecoder;
import io.netty.util.CharsetUtil;
import net.mamoe.mirai.MiraiServer;
public class MiraiUDPServer {
public MiraiUDPServer() {
MiraiServer.getInstance().getLogger().log("creating server");
new Thread(() -> {
Bootstrap b = new Bootstrap();
EventLoopGroup group = new NioEventLoopGroup();
b.group(group)
.channel(NioDatagramChannel.class)
.handler(new SimpleChannelInboundHandler<DatagramPacket>() {
protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet)
throws Exception {
// 读取收到的数据
ByteBuf buf = (ByteBuf) packet.copy().content();
byte[] req = new byte[buf.readableBytes()];
buf.readBytes(req);
String body = new String(req, CharsetUtil.UTF_8);
System.out.println("【NOTE】>>>>>> 收到客户端的数据:" + body);
// 回复一条信息给客户端
ctx.writeAndFlush(new DatagramPacket(
Unpooled.copiedBuffer("Hello我是Server我的时间戳是" + System.currentTimeMillis()
, CharsetUtil.UTF_8)
, packet.sender())).sync();
}
});
// 服务端监听在9999端口
try {
b.bind(9999).sync().channel().closeFuture().await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
MiraiServer.getInstance().getLogger().log("created server");
}
}

View File

@ -1,123 +0,0 @@
package net.mamoe.mirai.network;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import java.io.IOException;
/**
* 网络数据包接收器. 该类属于网络层, 插件一般不需要使用
*
* @author Him188 @ JPRE Project
*/
public class NetworkPacketHandler extends SimpleChannelInboundHandler<byte[]> {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
super.channelRead(ctx, msg);
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, byte[] data) throws Exception {
synchronized (this) {
handlePacket(ctx, data);
}
}
private byte[] temp = new byte[0];
/**
* Synchronized by {@code synchronized (this)} in {@link #channelRead0}
*/
private void handlePacket(ChannelHandlerContext ctx, byte[] data) {
/*try {
temp = Utils.arrayAppend(temp, data);
while (temp.length != 0) {
int position = Utils.arraySearch(temp, Protocol.SIGNATURE);
if (position < 0) {
return;//收到的是子包, 数据未结尾
}
byte[] d = Utils.arrayGetCenter(temp, 0, position);
temp = Utils.arrayDelete(temp, position + Protocol.SIGNATURE.length);
JPREMain.getInstance().getScheduler().addTask(() -> processPacket(ctx, d));
}
} catch (Exception e) {
e.printStackTrace();
}*/
}
//TODO 改为 public, 并将 ctx 改为插件可扩展的消息源以实现多源化
private void processPacket(ChannelHandlerContext ctx, byte[] data) {
if (data.length == 0) {
return;
}
processPacket(ctx, new BinaryStream());
}
private void processPacket(ChannelHandlerContext ctx, BinaryStream stream) {
//System.out.println(stream);
/*for (MPQClient client : clients) {
if (client.is((InetSocketAddress) ctx.channel().remoteAddress())) {
client.getFrame().getScheduler().addTask(() -> {
try {
client.dataReceive(stream);
} catch (Exception e) {
e.printStackTrace();
}
});
return;
}
}*/
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
if (cause instanceof IOException) { //远程主机强迫关闭了一个现有的连接
return;
}
super.exceptionCaught(ctx, cause);
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
super.channelActive(ctx);
/*
FrameConnectionEvent event = null;
for (MPQClient client : clients) {
if (client.is((InetSocketAddress) ctx.channel().remoteAddress())) {
event = new FrameConnectionEvent(client.getFrame());
client.setAddress((InetSocketAddress) ctx.channel().remoteAddress());
client.setCtx(ctx);
break;
}
}
if (event == null) {
Frame frame = new Frame(getJPREMain());
MPQClient client = new MPQClient(frame, (InetSocketAddress) ctx.channel().remoteAddress(), ctx);
clients.add(client);
event = new FrameConnectionEvent(frame);
}
event.getFrame().getPluginManager().callEvent(event);*/
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println("[Network] RemoteClient: " + ctx.channel().remoteAddress() + " disconnected.");
/*
for (MPQClient client : clients) {
if (client.is((InetSocketAddress) ctx.channel().remoteAddress())) {
FrameDisconnectionEvent event = new FrameDisconnectionEvent(client.getFrame());
client.getFrame().getPluginManager().callEvent(event);
break;
}
}
*/
super.channelInactive(ctx);
}
}