Exemplary network communication frame --KyroNet

Exemplary network communication frame --KyroNet

Brief introduction

  • KyroNet TCP and UDP is a Java package library, using the NIO connections, serialization data transmission using Kyro.
  • The main applications for client / server model, very efficient, especially for games
  • A similar framework: the Apache MINA , PyroNet , the Java Game Networking
  • GitHub repository KryoNet

Use

  • Maven dependency follows
<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>
  • Create a protocol class (JavaBean)
public class RequestProtocal {
	public int id;
	public String name;
	public String address;
}
public class ResponseProtocal {
	public int code;
	public String content;
}
  • Create server 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);
       }
    }
 });
  • Creating Client 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);
       }
    }
 });
Published 128 original articles · won praise 45 · Views 150,000 +

Guess you like

Origin blog.csdn.net/alionsss/article/details/103724663