Websocket communicating from jmonkey to c# fails

Hello everybody,

I have a question about communicating with a server on c# and a simulator in jmonkey using websockets.

I’m fairly new to websockets and that’s probably why I’m stuck at this moment.

In C# I have a little connection set up like this:

[java]
server = new TcpListener(IPAddress.Parse(“127.0.0.1”), port);

        server.Start();
        Console.WriteLine("Server has started on 127.0.0.1:"+ port +".{0}Waiting for a connection...", Environment.NewLine);

        client = server.AcceptTcpClient();

        Console.WriteLine("A client connected.");

        NetworkStream stream = client.GetStream();

        while(true)
        {
            //while (!stream.DataAvailable) ;
            if(stream.DataAvailable)
                Console.WriteLine(stream.Read(incoming,0,incoming.Length));
            
            if(client.Connected)
                stream.Write(outgoing,0,outgoing.Length);

            System.Threading.Thread.Sleep(500);
        }

[/java]

I think nothing is wrong with this code, correct me if I’m wrong.

Next I connect using the following code:

[java]package mygame;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;

/**
*

  • @author hreitsma
    */

public class Connection implements Runnable {

private int netPort = 1337;
private Socket socket;
private PrintWriter out;
private BufferedReader in;

private Intersection intersection;

public Connection(Intersection _intersection)
{
    this.intersection = _intersection;
}

@Override
public void run()
{
    connectToServer();
}

public synchronized void readCommand(String input) 
{
    intersection.getRoad(0).setTrafficLight(0);
}

private void connectToServer() 
{
    closeSocket();
    waitForServer();

    try {
        System.out.println("start reading");
        while(true)
        {
            System.out.println(in.read());  // this works like a charm
            out.write(11111);               // this gets lost or something like that :/
        }

// while ((line = in.readLine()) != null) {
// readCommand(line);
// }
} catch (SocketException ex) {
System.out.println(“Server has disconnected. Waiting for new server.”);
connectToServer();

    } catch (IOException e) {
        System.out.println("Cannot read line");
        connectToServer();
    }
}

public void waitForServer() 
{
    System.out.print("Waiting for server.");

    while (true) {
        try {
            socket = new Socket(InetAddress.getByName("127.0.0.1"), netPort);
            //socket = new Socket(InetAddress.getByName("192.168.2.2"), netPort);
            out = new PrintWriter(socket.getOutputStream());
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            System.out.println("Connected to server!");
            break;
        } catch (Exception e) {
            System.out.print(".");
        }

        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public void closeSocket() 
{

    if (socket != null) {
        if (!socket.isClosed()) {
            try {
                socket.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }
}

}
[/java]

When I start both programs the following happens:

server (C#):
Server has started on 127.0.0.1:1337
Waiting for a connection…
A client connected

client (JMonkey):
Waiting for server.
Connected to server!
start reading
0
1
0
1
1
etc…

JMonkey receives data perfectly, but C# doesn’t get data at all or JMonkey doesn’t send anything at all.

Can somebody explain what I’m totally doing wrong here?

Thanks a lot in advance!

I’m using port 1337 on both programs btw, I saw after posting that the value of port in the C# program wasn’t shown

try flushing the out stream.

Also, download and test with wireshark, as it cvan show you what actually happens on the network layer.
http://www.wireshark.org/download.html

On the server side I added stream.Flush(); within the while loop after the 500ms sleep.

Next I downloaded wireshark (nice program btw) but I can’t seem to catch the data.

I used a tutorial on how to filter and when I use: tcp.port == 1337 I don’t get any data, while the client does get data.
Also I tried changing from 127.0.0.1 to my local ip adress
And I tried changing from port 1337 to 80

Both actions had no result…

Am I doing something wrong here?

Probably, do you see traffic without any filters while surfing the web?

If not you might want to look if you have the correct interface captured.

Wish it was, when I filter on port 80 I get all traffic:

When I filter on port 1337 I get nothing, while firewall can’t be blocking it because my program does receive it, from server to client.

On windows? Might be routed trough a loopback socket ^^

I have checked it with Hercules, it’s a bit more simple for first time use.

I can connect to the C# server and send data, this is received by the server but only prints the length of the data.
Now I know that the C# program works nice and the JMonkey program could be wrong

As others have said, try flushing.
Instead of:
out.write(11111);

Do:
out.write(11111);
out.flush();

You may also have to disable Nagle’s algorithm… though I’d expect the flush to force it. http://docs.oracle.com/javase/6/docs/api/java/net/Socket.html#setTcpNoDelay(boolean)

Is this an existing server that you must communicate with or are you just making life harder for yourself?

Got it almost figured out now, thanks to you guys!
Only problem now is that when I use the current code, The program only sends something when it receives something.
I’m pretty sure this is because of in.read(); as long as it tries to read when there isn’t anything to read it will wait
At the C# program it’s the same story, it won’t do read and write both at the same time (after each other ofcourse).

[java]private void connectToServer()
{
closeSocket();
waitForServer();

    try {
        
        System.out.println("start reading");
        while(!stop)
        {
            System.out.println(in.read());  // this works like a charm
            out.print(22222);
            out.flush();
        }

// while ((line = in.readLine()) != null) {
// readCommand(line);
// }
} catch (SocketException ex) {
System.out.println(“Server has disconnected.”);
if(!stop)
{
System.out.println(“Waiting for new server.”);
connectToServer();
}

    } catch (IOException e) {
        System.out.println("Cannot read line");
        connectToServer();
    }
}[/java]

@pspeed
I just need to communicate between a controller program in C# and a simulator in JMonkey
If there is a simpler way I gladly want to hear it (:

You will want to thread the reading and writing or you will have constant issues. Threading the reading will clear up your problems with being able to write but you will likely want to thread writing too since it can backup if the TCP socket stalls.

I was just wondering if the C# server is really a requirement. If both halves are Java then it is easier to do because you could just use SpiderMonkey. Otherwise, there might be some existing cross platform network libraries that handle the complexities.

At this stage of your network-knowledge, you still have a lot of learning and hard-lessons ahead especially when working at this low level. If that’s the point then you are on the right track. But if the point is some end-goal other than “teach myself low-level networking architecture” then there are easier routes to take.

I will use the current class as the read Thread and start a new class with the write Threat
can I use the same connection for both Threads? if so, what is the best method for this? use it as a parameter at object initialize?

I would love to use only Java but one of the requirements is that I must use 2 different languages, so C# and Java was my first choice.

I’m glad you say that I’m on the right track, I understand Object Oriented Programming rather well now and I try to learn Threading and Sockets simultaneously
Both things separately are hard allready I think, so I’m just having a hard time now :stuck_out_tongue:

Other way round, but maybee this does help you

Apart from that the default behaviour for simple java networking would be:

One queue for to send objects
a thread that does write these objects from the queue too entwork infinitly

One thread that reads objects from the network
-> for simplification, just enqueue everything read to the renderthread, that way you get rid of almost all concurrency issues.