当前位置: 首页 > 工具软件 > KryoNet > 使用案例 >

网络通信框架——KyroNet示例

宫高义
2023-12-01

网络通信框架——KyroNet示例

简介

  • KyroNet是一款TCP和UDP的Java封装库,连接方式采用了NIO,传输数据的序列化方式采用了Kyro。
  • 主要用于client/server模式的应用,非常高效,特别适合游戏
  • 相似的框架: Apache MINAPyroNet Java Game Networking
  • GitHub仓库 KryoNet

使用方式

  • Maven依赖如下
<repositories>
   <repository>
      <id>clojars</id>
      <url>http://clojars.org/repo/</url>
   </repository>
</repositories>

<dependencies>
   <dependency>
      <groupId>kryonet</groupId>
      <artifactId>kryonet</artifactId>
      <version>2.21</version>
   </dependency>
</dependencies>
  • 创建协议类(JavaBean)
public class RequestProtocal {
	public int id;
	public String name;
	public String address;
}
public class ResponseProtocal {
	public int code;
	public String content;
}
  • 创建服务端 Server
 Server server = new Server();

// 在运行之前,记得对用到的协议类进行Kyro注册
 Kryo kryo = server.getKryo();
 kryo.register(RequestProtocal.class);
 kryo.register(ResponseProtocal.class);

// 启动服务端
 server.start();
 server.bind(54555, 54777); // 54555是TCP端口,54777是UDP端口

// 添加Listener回调,用于监听Client发送过来的请求
 server.addListener(new Listener() {
    public void received (Connection connection, Object object) {
       if (object instanceof RequestProtocal) {
          RequestProtocal request = (RequestProtocal)object;
          System.out.println(request.name);
 		
 		 // 向Client回传消息
          ResponseProtocal response = new ResponseProtocal();
          response.code = 123;
          response.content = "Hello World!";
          connection.sendTCP(response);
       }
    }
 });
  • 创建客户端 Client
 Client client = new Client();

 // 在运行之前,记得对用到的协议类进行Kyro注册
 Kryo kryo = client.getKryo();
 kryo.register(RequestProtocal.class);
 kryo.register(ResponseProtocal.class);

// 启动客户端
 client.start();
 // 超时时间, Server的IP, TCP端口, UDP端口
 client.connect(5000, "192.168.0.1", 54555, 54777);
 
 // 构建一个RequestProtocal,向Server发送消息
 RequestProtocal request = new RequestProtocal();
 request.id = 1;
 request.name = "xiaowang";
 request.address = "BeiJing";
 client.sendTCP(request);

// 监听服务端的响应信息
 client.addListener(new Listener() {
    public void received (Connection connection, Object object) {
       if (object instanceof ResponseProtocal) {
          ResponseProtocal response = (ResponseProtocal)object;
          System.out.println(response.content);
       }
    }
 });
 类似资料: