I am working on a project that involves sockets in local network - I want to make a Java server (desktop application running on Windows) that will listen to and make connections with several clients - Arduino boards.
The problem is, code sticks while trying to make a connection. Here's the Java code:
monitorThread = new Thread(() -> { try { System.out.println("Creating socket..."); ServerSocket server = new ServerSocket(4444); while (true) { System.out.println("Waiting for connection..."); Socket client = server.accept(); //NetworkManager.this.didConnect(client); System.out.println("Did establish connection"); if (delegate != null) { delegate.didConnect(client); } } } catch (IOException exception) { System.out.print(exception); } }); monitorThread.start();
and the Arduino code
#include <SPI.h> #include <Ethernet.h> IPAddress serverIp(192, 168, 1, 101); int serverPort = 4444; byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xEF }; IPAddress ip(192, 168, 1, 178); EthernetClient client; void setup() { Ethernet.begin(mac, ip); Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for native USB port only } delay(1000); // give the Ethernet shield a second to initialize: Serial.println("connecting..."); if (client.connect(serverIp, serverPort)) { Serial.println("connected."); } else { Serial.println("connection failed."); } }
What happens is both of those do not fail when trying to make a connection, but rather hang - Java server hangs on Socket client = server.accept();
, but Arduino hangs as well - on client.connect(serverIp, serverPort)
Computer running Java server has a static IP (192.168.1.101).
I understand Java's server.accept()
is a blocking call, so it will not proceed until a connection is made (what's why it runs in a separate thread), but what puzzles me is why Arduino hands as well.
Even if I try to connect to some other server IP and port - for example 64.233.187.99
(Google), it still hangs.
What am I doing wrong? Is there some additional setup that I haven't done? Can it have something to do with my network's settings?
1 Answers
Answers 1
Kindly try these steps and give it a try:
- Turn off firewall on Windows (Java Server)
- Check from another network connected pc that you can connect (telnet) to 192.168.1.101 on port 4444 (ie: telnet 192.168.1.101 4444)
- Change delay(1000) line to delay(5000) to give arduino ethernet shield more time to initialize
Also please post your loop code. I am using exactly the same code to communicate arduino to a java socket server. Your code seems fine; it might be firewall or something. Make sure you check out telnet connection from another machine.
0 comments:
Post a Comment