网络通信框架——KyroNet示例
简介
使用方式
<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>
public class RequestProtocal {
public int id;
public String name;
public String address;
}
public class ResponseProtocal {
public int code;
public String content;
}
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 = 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);
}
}
});