Java ServerSocket and Arduino Ethernet Client

I currently have a Java Server Socket based server set up, and I want to send data to it using the Ethernet client, however, every time I call client.Connect it returns that it failed to connect to the client.

Specifically this code executes:
(data is an integer)

void sendData(int data) {
  if ((data <= lastValue-tolerance) || (data >= lastValue+tolerance)) {
    Serial.println(data);
    lastValue = data;
    if (client.connect(serverIP,port)) {
      addToMsgList("Connected to Server!");
      client.print(1);//Sync ID for the server
     client.print(data); //actual data
    } else {
     Serial.println("Failed to connect to Server"); 
    }
  }
}

and this is the output:

422
Failed to connect to Server

where 422 is the data


So the question is:
why can the Arduino not see the java ServerSocket based server.

Java Server code below,

		int PortNumber = this.serverPort;
		ServerSocket serverSock;
		try {
			serverSock = new ServerSocket(PortNumber);

			while (endServer != true) {
				// accept connections and pass to client threads
				
				Socket clientSocket = serverSock.accept();
				ArdunioReceiveThread receiveThread = new ArdunioReceiveThread(clientSocket);
				Thread runableReceiveThread = new Thread(receiveThread);
				runableReceiveThread.start();
				
			}
			serverSock.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

(ArduinoReceiveThread)

	public void run() {
		try {
		InputStream is = this.clientSocket.getInputStream();
		DataInputStream dis = new DataInputStream(is);
		while (is.available()>0) {
			DebugSuite.conditionalOutput(""+is.read(),showOutput);
		}
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	}

Both programs are missing the important stuff.

What IP is assigned to the Java server? What port is it listening on? Is the server firewall allowing that port through?

What serverIP is the Arduino using to connect? What port?

The server is listening on port 12000
the client is sending data on port 12000
the server firewall is disabled
the server ip is the ip of the computer with the java server (local network, 192.168.1.108)

And you can connect to the java server with a PC on that localnet? PuTTY (network app) should be able to connect.

So you have this in your global variables?

IPAddress serverIP(192,168,1,108);
unsigned int port = 12000;

Can you ping the Arduino from the server?

Regards, Ray L.

Simple client test code you can try to see if you can connect to a server.

//zoomkat 3-1-13
//simple client checkip test
//for use with IDE 1.0.1 or later
//with DNS, DHCP, and Host
//open serial monitor and send an e to test
//for use with W5100 based ethernet shields

#include <SPI.h>
#include <Ethernet.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //physical mac address

char serverName[] = "checkip.dyndns.com"; // test web page server
EthernetClient client;

//////////////////////

void setup(){

  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // no point in carrying on, so do nothing forevermore:
    while(true);
  }

  Serial.begin(9600); 
  Serial.println("Better client ip test 3/1/13"); // so I can keep track of what is loaded
  Serial.println("Send an e in serial monitor to test"); // what to do to test
}

void loop(){
  // check for serial input
  if (Serial.available() > 0) //if something in serial buffer
  {
    byte inChar; // sets inChar as a byte
    inChar = Serial.read(); //gets byte from buffer
    if(inChar == 'e') // checks to see byte is an e
    {
      sendGET(); // call sendGET function below when byte is an e
    }
  }  
} 

//////////////////////////

void sendGET() //client function to send/receive GET request data.
{
  if (client.connect(serverName, 80)) {  //starts client connection, checks for connection
    Serial.println("connected");
    client.println("GET / HTTP/1.0"); //download text
    client.println("Host: checkip.dyndns.com");
    client.println(); //end of get request
  } 
  else {
    Serial.println("connection failed"); //error message if no client connect
    Serial.println();
  }

  while(client.connected() && !client.available()) delay(1); //waits for data
  while (client.connected() || client.available()) { //connected or data available
    char c = client.read(); //gets byte from ethernet buffer
    Serial.print(c); //prints byte to serial monitor 
  }

  Serial.println();
  Serial.println("disconnecting.");
  Serial.println("==================");
  Serial.println();
  client.stop(); //stop client

}

I was not able to ping it, and when I ran the program zoomkat posted and the connection failed. I tried updating the program with my mac address listed on the Galileo module, and it still failed.

so I suppose the issue isn't with the java socket server yet, it's with the Galileo.

Better client ip test 3/1/13
Send an e in serial monitor to test
connection failed


disconnecting.
==================

ok, now it seems to work, problem was not having the sd card with yocto linux on it. While it says it has the wifi drivers, I guess they failed to mention it also has the ethernet drivers on it too. Galileo Gen 2 specific issue I guess. Now the problem is connecting to the java server socket. I can now ping the Galileo, and I can run the sketch posted above, which prints out a lot of "y" like characters and more or less crashes (That is what it is supposed to do I assume).

I can now ping the Galileo, and I can run the sketch posted above, which prints out a lot of "y" like characters and more or less crashes (That is what it is supposed to do I assume).

This is what it will do, not what is is supposed to do.

This section of zoomkat's code is the reason you get the funny y. If the client is connected OR has characters available, it reads and prints the character. So if the client is connected and there are no characters available, it reads the rx buffer, but the client.read() will return -1 (255 unsigned), which is the funny y.

  while (client.connected() || client.available()) { //connected or data available
    char c = client.read(); //gets byte from ethernet buffer
    Serial.print(c); //prints byte to serial monitor 
  }

Funny y = ÿ

The correct "Perfect World" code is this.

while(client.connected()) {
  while(client.available()) {
    char c = client.read();
    Serial.print(c);
  }
}

edit: If you want the "Real World" version, that is here: http://playground.arduino.cc/Code/WebClient It has a timeout that will prevent the code from "crashing".

The correct "Perfect World" code is this.

It will be interesting to see if that actually fixes the OP's issue.

zoomkat: It will be interesting to see if that actually fixes the OP's issue.

Probably not. I presume it is the Java server that is causing the fail, but your client code can't deal with the failure. Without the timeout feature of my code in the playground, the "Perfect World" code will lock up also.

Probably not.

That is my thinking too. 8)

Just by looking at the OP’s code, it is the ArduinoReceiveThread that is not closing the connection. It appears it is not even sending a response to the client. I don’t know how the Galileo wifi (if that is what the OP is using according to reply#7) will handle that.

This appears to be a software caused server stall. Server stalls happen more often that one would think for various reasons besides faulty software. Overloading and rogue client requests can also cause them. The timeout feature in my code will close the connection if the server stalls for more than 10 seconds.

Broken connections happen now and then, which will also cause a lockup without a timeout feature in the client code.

That is why my client code in the playground has a timeout. It will survive even if the server does not.

I am a bit confused, what do you mean the timeout feature? did you modify the ethernet.h and .cpp files? how are you communicating with your device, is there something else I could try? I really don't want to use UDP or something similar if I can avoid it.

josh90301: I am a bit confused, what do you mean the timeout feature? did you modify the ethernet.h and .cpp files? how are you communicating with your device, is there something else I could try? I really don't want to use UDP or something similar if I can avoid it.

No.

This is the timeout section. If the server fails to send a disconnect message, the "while(client.connected())" loop becomes an endless loop and never exits without this timeout. That gives the appearance the code froze (edit: or in zoomkat's code, displays an endless stream of the character ÿ). The timeout closes the connection on the client end if the client does not receive a packet from the server for 10 seconds.

// connectLoop controls the hardware fail timeout
  int connectLoop = 0;

  while(client.connected())
  {
    while(client.available())
    {
      inChar = client.read();
      Serial.write(inChar);
      // set connectLoop to zero if a packet arrives
      connectLoop = 0;
    }

    connectLoop++;

    // if more than 10000 milliseconds since the last packet
    if(connectLoop > 10000)
    {
      // then close the connection from this end.
      Serial.println();
      Serial.println(F("Timeout"));
      client.stop();
    }
    // this is a delay for the connectLoop timing
    delay(1);
  }

  Serial.println();

  Serial.println(F("disconnecting."));
  // close client end
  client.stop();

Hey, Just wanted to thank you guys for your help, also I managed to get something similar working. if I make the device into an “Ethernet Server” and connect to it with a java Socket, it seems to work, I don’t know exactly why this works, but it does.

The same issue occurred with a spark core, both devices handle a lot more networking “behind the scenes.”
(dhcp, ect).

I haven’t seen one of these threads (involving the java socket servers) get resolved, so I hope this can be helpful.

#include <Dhcp.h>
#include <Dns.h>
#include <Ethernet.h>
#include <EthernetClient.h>
#include <EthernetServer.h>
#include <EthernetUdp.h>

byte mac[] = {0x98,0x4F,0xEE,0x01,0xD3,0x96};
byte ip[] = { 192, 168, 1, 201 };    
// the router's gateway address:
byte gateway[] = { 192, 168, 1, 1 };
// the subnet:
byte subnet[] = { 255, 255, 255, 0 };

// telnet defaults to port 23
EthernetServer server = EthernetServer(23);

void setup()
{
  // initialize the ethernet device
  Ethernet.begin(mac, ip, gateway, subnet);

  // start listening for clients
  server.begin();
}

void loop()
{
  // if an incoming client connects, there will be bytes available to read:
  EthernetClient client = server.available();
  if (client == true) {
    // read bytes from the incoming client and write them back
    // to any clients connected to the server:
    server.write("This will appear every time.\n");
  }
}

“java client server”

public class Main {

	private static final int port = 23;//port to listen on
	
	public static void main(String[] args) throws UnknownHostException, IOException {
		// TODO Auto-generated method stub
		
		Socket sock = new Socket("192.168.1.133",port);
		Scanner inputScanner = new Scanner(sock.getInputStream());
		
		while (true) {
			System.out.println(inputScanner.nextLine());
			System.out.flush();
		}
	}

}

It’s not a prefect fix, and this isn’t quite as easy to get information from, I’ll be creating a new connection manager to handle connections in this way, (using threads), but this code might work, also if you notice, I specify the ip 192.168.1.133, despite setting the static IP in the arduino code to 192.168.1.201. It just seems to ignore starting the ethernet connection, so if one is using an ethernet sheild, a fair bit more toying with may be required, but the concept remains the same.