EzDevInfo.com

kryonet

TCP/UDP client/server library for Java, based on Kryo

Kryonet -- How can I register classes within my class?

I have the following class:

public class QueryResults {
    protected Set<String> resultList = new HashSet<String>();
    protected long executionTime = 0;

    public long getExecutionTime() { return executionTime; }
    [...]
}

And I register it as so:

Registrar.RegisterClass(this, QueryResults.class);
------------
public class Registrar {
    public static void RegisterClass(Node n, Class theClass) {
        Map<String, Node> nodeMap = Node.getNodeMap();
        for (Map.Entry<String, Node> node : nodeMap.entrySet()) {
            if (node.getKey().equals(n.getHostname())) {
                Log.info("Registering " + theClass.getSimpleName() + " for " + node.getValue().getHostname());
                node.getValue().getServer().getConnection().getKryo().register(theClass);
                node.getValue().getClient().getConnection().getKryo().register(theClass);
            }
        }
    }
}

This has worked well until attempting to serialize QueryResults, due to it containing a container, in this case a HashSet (We've tried an ArrayList as well, with the same results).

On the endpoint populating and ultimately serializing this class to send back to the caller, I get this output:

Exception in thread "Server" com.esotericsoftware.kryo.KryoException:
java.lang.IllegalArgumentException: Class is not registered: java.util.HashSet

Note: To register this class use: kryo.register(java.util.HashSet.class);

If I explicitly call Registrar.RegisterClass(this, HashSet.class);, everything works swimmingly. However, this can be annoying once we start to implement more advanced classes, with many types of containers.

Am I doing something wrong?


Source: (StackOverflow)

Kryonet disconnects just after connecting

I followed this Youtube tutorial covering the basics of Kryonet.

Basically it is a Kryonet Hello World, it explains how to setup a basic Server and a Client, allowing the Client to send Packets to the Server and have very basic communication.

A link to the source code. Both Server and Client have the same Packet class.

I can get the Server running, and the Client asking the IP to connect. However when i enter the IP, the Client terminates just after connecting.

Client output:

00:03  INFO: Connecting: /127.0.0.1:54555
00:03  INFO: [kryonet] Connection 1 connected: /127.0.0.1
00:03  INFO: [CLIENT] You have connected.
BUILD SUCCESSFUL (total time: 3 seconds)

The Server command line Log:

00:00  INFO: [kryonet] Server opened.
00:04 DEBUG: [kryonet] Port 54555/TCP connected to: /127.0.0.1:53217
00:04 DEBUG: [kryo] Write: RegisterTCP
00:04  INFO: [kryonet] Connection 1 connected: /127.0.0.1
00:04  INFO: [SERVER] Someone has connected.
00:04 DEBUG: [kryonet] Connection 1 update: Se ha forzado la interrupcion de una
 conexion existente por el host remoto
00:04  INFO: [SERVER] Someone has disconnected.
00:04  INFO: [kryonet] Connection 1 disconnected.

It seems like the system closes the TCP connection, but i don't really know. Must i enable something in Windows or/and router to permit communication of Kryonet?

Can somebody spot the problem? Thanks in advance.

The line that appears in spanish in the command line log is something like "An interruption of an existant connection has been forced by the remote host."

EDIT after user1816380 advice:

Most of times it still shows the original error, but from time to time you can see:

00:00  INFO: [kryonet] Server opened.
00:07 DEBUG: [kryonet] Port 54555/TCP connected to: /127.0.0.1:50787
00:07 DEBUG: [kryo] Write: RegisterTCP
00:07  INFO: [kryonet] Connection 1 connected: /127.0.0.1
00:07  INFO: [SERVER] Someone has connected.
00:07 DEBUG: [kryo] Read: Packet0LoginRequest
00:07 DEBUG: [kryonet] Connection 1 received TCP: Packet0LoginRequest
00:07 DEBUG: [kryo] Write: Packet1LoginAnswer
00:07 DEBUG: [kryonet] Connection 1 sent TCP: Packet1LoginAnswer (6)
00:07 DEBUG: [kryonet] Connection 1 update: Se ha forzado la interrupcion de una
 conexion existente por el host remoto
00:07  INFO: [SERVER] Someone has disconnected.
00:07  INFO: [kryonet] Connection 1 disconnected.

Source: (StackOverflow)

Advertisements

Java Kryonet servers, client not receiving server response

I am trying to teach myself some networking in Java using the Kryonet library. The following code is almost identical to the code in the kyronet tutorial. https://code.google.com/p/kryonet/#Running_a_server

The client is successfully sending the message "Here is the request!" to the server (the server is printing it out) however the client is not receiving any response from the server even though the server is sending one.

I've tried unsuccessfully to fix it, can anyone see or suggest a possible problem/solution with the code?

(The code follows)

Client

public class Client_test {
Client client = new Client();
public Client_test() {
    Kryo kryo = client.getKryo();
    kryo.register(SomeRequest.class);
    kryo.register(SomeResponse.class);
    client.start();
    try {
        client.connect(50000, "127.0.0.1", 54555, 54777);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    client.addListener(new Listener() {
           public void received (Connection connection, Object object) {
              if (object instanceof SomeResponse) {       
                 SomeResponse response = (SomeResponse)object;
                 System.out.println(response.text);
              }
           }
        });
    SomeRequest request = new SomeRequest();
    request.text = "Here is the request!";
    client.sendTCP(request);

}

}

Server

public class ServerGame {
Server server = new Server();

public ServerGame() {
    Kryo kryo = server.getKryo();
    kryo.register(SomeRequest.class);
    kryo.register(SomeResponse.class);
    server.start();
    try {
        server.bind(54555, 54777);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    server.addListener(new Listener() {
           public void received (Connection connection, Object object) {
              if (object instanceof SomeRequest) {
                 SomeRequest request = (SomeRequest)object;
                 System.out.println(request.text);
                 SomeResponse response = new SomeResponse();
                 response.text = "Thanks!";
                 connection.sendTCP(response);
              }
           }
        });
}

}

Response & Request classes

public class SomeRequest {
public String text;
public SomeRequest(){}
}

public class SomeResponse {
public String text;
public SomeResponse(){}
}

Source: (StackOverflow)

Java Kryonet [Class is not registered Exception ]

I found this API called Kryonet. Well, i tried to implement the example provided in the project page. However, it wasn't successful.

Server code:

public class KryoTest {

public KryoTest() throws IOException {
    Server server = new Server();
    server.start();
    server.bind(54555, 54777);
    server.addListener(new Listener() {

        public void received(Connection connection, Object object) {
            if (object instanceof SomeRequest) {
                SomeRequest request = (SomeRequest) object;
                System.out.println(request.text);

                SomeResponse response = new SomeResponse();
                response.text = "Thanks!";
                connection.sendTCP(response);
            }
        }
    });
    Kryo kryo = server.getKryo();
    kryo.register(SomeRequest.class);
    kryo.register(SomeResponse.class);
}

public static void main(String[] args) throws IOException {
    new KryoTest();
}}

Client Code:

    public class Kryoclient {

    public Kryoclient() throws IOException {
    Client client = new Client();
client.start();
client.connect(5000,"192.168.1.4", 54555, 54777);

SomeRequest request = new SomeRequest();
request.text = "Here is the request!";
client.sendTCP(request);

 Kryo kryo = client.getKryo();
kryo.register(SomeRequest.class);
kryo.register(SomeResponse.class);

}
    public static void main(String[] args) throws IOException {
        new Kryoclient();
    }
}

Exception:

run:
00:00  INFO: Connecting: /192.168.1.4:54555/54777
00:00  INFO: [kryonet] Connection 1 connected: /192.168.1.4
Exception in thread "main" java.lang.IllegalArgumentException: Class is not registered: client.SomeRequest
    at com.esotericsoftware.kryo.Kryo.getRegisteredClass(Kryo.java:319)
    at com.esotericsoftware.kryo.Kryo.writeClass(Kryo.java:374)
    at com.esotericsoftware.kryo.Kryo.writeClassAndObject(Kryo.java:484)
    at com.esotericsoftware.kryonet.TcpConnection.send(TcpConnection.java:196)
    at com.esotericsoftware.kryonet.Connection.sendTCP(Connection.java:68)
    at client.Kryoclient.<init>(Kryoclient.java:24)
    at client.Kryoclient.main(Kryoclient.java:30)

What is wrong with this code?


Source: (StackOverflow)

libgdx & kryonet: threads

I try to develop a game for Android platform, using Libgdx library. For network, I use the Kryonet library.

I want to change screen when I'm sure that my application is connected to my server.
The network part seems work but I have a problem with threads: it's the Kryonet's thread which execute OpenGL, not the Libgdx thread:

public class MyGdxGame extends Game {
    public static int UDP_PORT = 55555, TCP_PORT = 55556;
    private Client client;

    @Override
    public void create() {
        /*
         * client connection
         * etc ...
         */
        client.addListener(new Listener() {
            private int nb = 0;

            @Override
            public void received(Connection connection, Object data) {
                super.received(connection, data);
                nb++;
                if (nb == 5) {
                    MyGdxGame.this.setSecondScreen();
                }
            }
        });
        setScreen(new First(this, client));
    }

    protected void setSecondScreen() {
        setScreen(new Second(this, client)); //This part should be executed by Libgdx thread ?!     
    }

Note that First and Second are both Screen class which just draw an image.

I have this exception when I try to launch Second Screen: Exception in thread "Client" java.lang.RuntimeException: No OpenGL context found in the current thread.

Can I force the LibGDX thread to execute instructions ? Is an other approach possible?

Thank's Jonathan


Source: (StackOverflow)

Running a method from an object in another Thread

I have LibGDX Application in which I paint and a Thread for Client or Server. Connections are done using Kryonet. When your opponent creates does something a message is recieved linke so:

public void received(Connection con, Object object) {

                            TroopMessage tm = (TroopMessage)object;                         
                            fortress.map.addSoldier(tm.kind, true);
                            System.out.println("recieved");

                            connection = con;
}

When this callback is called (and it is correctly) I get "No OpenGL context found in the current thread". I think it is looking for the object fortress within the MyClient Thread. I want to call to fortress.map.addSoldier which refers to an object currently existing in another thread.

public class Fortress extends Game implements ApplicationListener{
    private OrthographicCamera camera;
    private SpriteBatch batcher;

    public static MyServer server;
    public static MyClient client;

    public static Map map;
[....]

How can I call the method in from another thread?

thanks in advance


Source: (StackOverflow)

android game server not working using kryonet + LibGdx !! hallpp

I am currently developing an android multiplayer game (one on one fighting) using libgdx graphics api and the kryonet api for all server client networking . In case you might not know , libgdx is an open source java api for game development . Kryonet is an independent networking api suitable for games pc,android and linux . So far everything is going good ,... made a server , 2 clients as players .

I tried running server and clients in pc . Its working . I then tried running server on pc and player clients in android phone . Its working .

But... the problem happend when i use my android phone as a server . my client program cannot discover the android server . I even made sure i used the ip of my phone from whatsmyip.com . But my android server is still invisible . I made sure i set the manifests correctly with the internet permissions .

Is it even possible to run an android phone as a server due to its mobild ip ? I badly need to make this work so that a central server is not needed . Players can simply play in a p2p fashion where one players starts a server and the other player just joins the server player .


Source: (StackOverflow)

StackOverflow when using Kryo to serialize objects with references to each other

I have a graph-like object that I'm sending from server to client that contains nodes that have adjacencyLists.

I have something similar to this:

Clearing c1 = new Clearing(1, 134, 151);
Clearing c6 = new Clearing(6, 250, 88);

c1.adjacentByPath.add(new Path(1, c6));
c6.adjacentByPath.add(new Path(1, c1));

Each time I send the object that contains these clearings, I receive the following error:

Exception in thread "Server" java.lang.StackOverflowError
at com.esotericsoftware.kryo.Kryo.getRegistration(Kryo.java:448)
at com.esotericsoftware.kryo.util.DefaultClassResolver.writeClass(DefaultClassResolver.java:79)
    ......

Is there a workaround for this in Kryonet? Thanks


Source: (StackOverflow)

Java: How to force upcast?

I'm using the Kryo library for serialization in Java. I have a problem where I have no way to force an upcast. Here is an example situation:

class A {}
class B extends A {}

public save() {
    Kryo kryo = new Kryo();
    kryo.setRegistrationRequired(true); //force registration
    kryo.register(A.class); //register A with kryo
    Output output = new Output( ... );

    B bar = new B();
    kryo.writeObject(output, (A) bar); //try to cast it up
}

This causes an class not registered error, because bar is still an instance of B.

Is there any way to force bar to be cast up to an instance of A, or will I need to do something like new A(bar)?


Source: (StackOverflow)

Using kryonet and amazon aws elastic beanstalk

Does anyone have any experience they could share with deploying a kryonet server within an amazon aws elastic beanstalk?

And a more specific question - do you have to use a fixed ip-address or can it work via the beanstalk's url? If you need to use a fixed ip-address, how does this impact the beanstalk's scaling up?


Source: (StackOverflow)

Kryonet and Slick2D

I'm trying to integrate Kryonet within a Slick2D game with the assistance of this tutorial. I'm trying to create a server/client infrastructure where a user can either create a server or join a server to play a two player game.

The tutorial suggests adding the overall game object as a "network listener," however in my Slick2D game the GameContainer and StateBasedGame are only available across the whole application.

The GameContainer wraps my game object and this game object extends StateBasedGame. I have no idea how to integrate KryoNet.

I'm really struggling to find info that can help me so any guidance at all would be great.


Source: (StackOverflow)

Java System.out.println() affecting program flow [duplicate]

This question already has an answer here:

I am working on a server/client based game using the KryoNet java library as well as slick. When the server class receives a connection from a client, it sends necessary startup information to the client, including what player number it is. One receiving this, the client starts slick and begins operating normally. The code for this is:

    boolean started = false;
    while(!started){
        System.out.println(cs.playerNum);
        if(cs.playerNum != -1){
            cs.startSlick();
            started = true;
        }
    }

The playerNum is set by another thread when the value is received from the server. For a while I could not get this to work (cs.startSlick() was never called), and eventually I got frustrated and began logging playerNum each time the loop ran. By adding System.out.println(cs.playerNum), the code began working, the loop would evaluate properly and slick would be started.

How is it possible that System.out.println does this? I have tried replacing it with other functions, and even other functions which take cs.playerNum as a parameter, but only when I specifically print cs.playerNum can I get the loop to work. If I need to include more source I can, but the issue seems to be directly here since I have tried replacing System.out.println with other functions to no success.


Source: (StackOverflow)

Sending and receiving arrays in kryonet

I'm using kryonet to create a Server/Client system.

I'm trying to send an int[][] to my client, from the server. To achieve this task I tried this:

publc class ArrayPacket {
 public int[][] array
}

Then, in the server listener I wrote:

ArrayPacket myPacket = new ArrayPacket();
for (int y = 0; y < Level.height; y++) {
    for (int x = 0; x < Level.width; x++) {
        myPacket.id[x][y] = somethingAt[x][y];
    }
}
clientConnection.sendTCP(myPacket);

Finally, in the client listener I receive the ArrayPacket:

public void received(Connection con, Object object) {
            if (object instanceof ArrayPacket) {
                for (int y = 0; y < Level.height; y++) {
                    for (int x = 0; x < Level.width; x++) {             
                        somethingAt[x][y] = ((ArrayPacket) object).array[x][y];
                    }
                }
            }
        }

And I register everything like that:

public void register(Kryo k) {
    k.register(ArrayPacket.class);
    k.register(int[][].class);
}

However, when I run it throws me an error saying that I must register the int[].class. So I do that, run the program again, and the compiler throws me a BufferOverflowException:

Exception in thread "Server" com.esotericsoftware.kryo.KryoException: java.nio.BufferOverflowException
Serialization trace:
array (myPackage.ArrayPacket)
    at com.esotericsoftware.kryo.serializers.FieldSerializer$ObjectField.write(FieldSerializer.java:585)
    at com.esotericsoftware.kryo.serializers.FieldSerializer.write(FieldSerializer.java:213)
    at com.esotericsoftware.kryo.Kryo.writeClassAndObject(Kryo.java:571)
    at com.esotericsoftware.kryonet.KryoSerialization.write(KryoSerialization.java:50)
    at com.esotericsoftware.kryonet.TcpConnection.send(TcpConnection.java:192)
    at com.esotericsoftware.kryonet.Connection.sendTCP(Connection.java:59)
    at myPackage.MyServerListener.received(ServerListener.java:28)
    at com.esotericsoftware.kryonet.Server$1.received(Server.java:61)
    at com.esotericsoftware.kryonet.Connection.notifyReceived(Connection.java:246)
    at com.esotericsoftware.kryonet.Server.update(Server.java:208)
    at com.esotericsoftware.kryonet.Server.run(Server.java:356)
    at java.lang.Thread.run(Thread.java:724)

Caused by: java.nio.BufferOverflowException
    at java.nio.HeapByteBuffer.put(HeapByteBuffer.java:183)
    at com.esotericsoftware.kryo.io.ByteBufferOutputStream.write(ByteBufferOutputStream.java:42)
    at com.esotericsoftware.kryo.io.Output.flush(Output.java:154)
    at com.esotericsoftware.kryo.io.Output.require(Output.java:134)
    at com.esotericsoftware.kryo.io.Output.writeInt(Output.java:246)
    at com.esotericsoftware.kryo.serializers.DefaultArraySerializers$IntArraySerializer.write(DefaultArraySerializers.java:55)
    at com.esotericsoftware.kryo.serializers.DefaultArraySerializers$IntArraySerializer.write(DefaultArraySerializers.java:45)
    at com.esotericsoftware.kryo.Kryo.writeObjectOrNull(Kryo.java:552)
    at com.esotericsoftware.kryo.serializers.DefaultArraySerializers$ObjectArraySerializer.write(DefaultArraySerializers.java:312)
    at com.esotericsoftware.kryo.serializers.DefaultArraySerializers$ObjectArraySerializer.write(DefaultArraySerializers.java:293)
    at com.esotericsoftware.kryo.Kryo.writeObjectOrNull(Kryo.java:552)
    at com.esotericsoftware.kryo.serializers.FieldSerializer$ObjectField.write(FieldSerializer.java:570)
    ... 11 more

So, how can I fix this error?

Thanks in advance.


Source: (StackOverflow)

Kryonet Exception when casting received Object (Bug?)

I have this small piece of code in my class which extends Listener:

@Override
public void received(Connection connection, Object object)
{
    Packet packet = (Packet) object;
    server.addPacket(new ClientPacket(connection.getID(), packet));
}

Whenever I receive an Object, I cast it to an Interface called Packet with a method handle() which every packet implement. I then add it to a ConcurrentLinkedQueue for future processing.

Still, after i spam a few keys which send UDP packets to the server, the following Exception is thrown:

Exception in thread "Server" java.lang.ClassCastException: com.esotericsoftware.kryonet.FrameworkMessage$KeepAlive cannot be cast to com.xkynar.game.net.packet.Packet at com.xkynar.game.net.ServerSocket.received(ServerSocket.java:70) at com.esotericsoftware.kryonet.Server$1.received(Server.java:61) at com.esotericsoftware.kryonet.Connection.notifyReceived(Connection.java:246) at com.esotericsoftware.kryonet.Server.update(Server.java:208) at com.esotericsoftware.kryonet.Server.run(Server.java:356) at java.lang.Thread.run(Unknown Source)

The exception occurs in the cast, that is:

Packet packet = (Packet) object;

How can this be possible? What the hell is "FrameworkMessage$KeepAlive" to begin with? Why is it entering my received listener?

Please explain what is wrong, is it my mistake or a bug?


Source: (StackOverflow)

Problems porting Kryonet library from jar to GWT format

I'm trying to port the Kryonet to the GWT format. I'm building the GWT.XML but when I launch my GWT app, I have 2 error reported (I don't know where).

I put the code here. Can you help me to port this wonderful library to the GWT compiler?

kryonet.gwt.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit trunk//EN" "http://google-web-toolkit.googlecode.com/svn/trunk/distro-source/core/src/gwt-module.dtd">
<module rename-to="com.esotericsoftware.kryonet">
    <source path="kryonet">
        <include name="Client.java"/>
        <include name="Connection.java"/>
        <include name="EndPoint.java"/>
        <include name="FrameworkMessage.java"/>
        <include name="JsonSerialization.java"/>
        <include name="KryoNetException.java"/>
        <include name="KryoSerialization.java"/>
        <include name="Listener.java"/>
        <include name="Serialization.java"/>
        <include name="Server.java"/>
        <include name="TcpConnection.java"/>
        <include name="UdpConnection.java"/>
        <include name="rmi/ObjectSpace.java"/>
        <include name="rmi/RemoteObject.java"/>
        <include name="rmi/TimeoutException.java"/>
        <include name="util/InputStreamSender.java"/>
        <include name="util/TcpIdleSender.java"/>
    </source>   
</module>

Source: (StackOverflow)