我使用Kryo-net发送和接收消息。在服务器端,我打开新线程并设置服务器,问题是线程在代码末尾结束,因此没有真正的请求侦听器。
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryonet.Connection;
import com.esotericsoftware.kryonet.Listener;
import com.esotericsoftware.kryonet.Server;
public class MessagingServer implements Runnable{
private Server server;
public void stop(){
this.server.stop();
}
public MessagingServer(){
this.server = new Server();
}
@Override
public void run() {
try{
if(server!=null){ stop(); }
this.server.start();
this.server.bind(54555, 54777);
Kryo kryo = this.server.getKryo();
kryo.register(NewRequiredJobRequest.class);
kryo.register(NewRequiredJobResponse.class);
server.addListener(new Listener() {
@Override
public void received (Connection connection, Object object) {
if (object instanceof HelloRequest) {
HelloRequest request = (HelloRequest)object;
System.out.println(request.text);
HelloResponse response = new HelloResponse();
response.text = "Thanks!";
connection.sendTCP(response);
}
}
});
} catch (Exception e) {
System.out.println("kryo server exception"));
}
// once the code reach here the thread is ended..
}
}