Reputation: 664
Hi I am using Kryonet as my network library for the game I'm developing.
I've got this code in the server side:
public class MyServer {
Kryo kryo;
Server server;
Connection connection;
public MyServer(){
server = new Server();
server.start();
try {
server.bind(59990, 59900);
} catch (IOException e) {
System.out.println("FATAL ERROR");
}
kryo = server.getKryo();
kryo.register(Message.class);
server.addListener(new Listener() {
public void received (Connection con, Message str) {
System.out.println("Message recieved from client to server");
Message m = (Message)str;
System.out.println(m.text);
}
public void connected(Connection con){
System.out.println("Hey, we are connected!");
connection = con;
con.sendTCP("HOLA CLIENTE!!");
}
public void disconnected(Connection con){
System.out.println(":( He is gone... he'll never come back..");
}
});
}
public void sendMessage(String tipoMensaje,String tipoTropa,String id){
connection.sendTCP(tipoMensaje+"-"+tipoTropa+"-"+id);
}
}
And this in the client side:
public class MyClient {
Client client;
Connection connection;
Kryo kryo;
public MyClient(){
client = new Client();
client.start();
try {
kryo = client.getKryo();
kryo.register(Message.class);
client.connect(5000, "10.211.55.3", 59990, 59900);
//sendMessage("fromclient","ee","ee");
client.addListener(new Listener() {
public void received (Connection con, String str) {
System.out.println(str);
System.out.println("Message recieved from server to client");
}
public void connected(Connection con){
System.out.println("Hey, we are connected!");
connection = con;
Message m = new Message();
m.text="eeep";
client.sendTCP(m);
}
public void disconnected(Connection con){
System.out.println(":( He is gone... he'll never come back..");
}
});
} catch (IOException e) {
System.out.println("Error while connecting");
}
}
public void sendMessage(String tipoMensaje,String tipoTropa,String id){
client.sendTCP(tipoMensaje+"-"+tipoTropa+"-"+id);
System.out.println("Message sent from client to server");
}
}
Message is just a class with a string in it. When I try to connect client to the server I get the "Hey, we are connected!" message and afterwards a "Message recieved from client to server" in the server's command line. However, m.text (the content of the message) is not printed and I don't know why.
Thanks in advance.
Upvotes: 0
Views: 1186
Reputation: 3149
It's because there is no method public void received (Connection con, String str)
in a Listener - basically, your server never calls it. This is also a reason why you should use @Override
- you wouldn't have this problem in the first place.
Replace String str
with Object o
. Then - check if your object is actually a Message
. If it is, cast it to a Message
and print out its text. Your method should look like this:
@Override
public void received(Connection connection, Object packet) {
if (packet instanceof Message) {
System.out.println(((Message) packet).text);
}
}
Upvotes: 3