ESP8266 suddenly stopped connecting to java server - java

I have a java program on a computer that is the server and a program on the esp that acts as a client. They both connect to the local wifi and then to each other. The purpose is to have the computer send a number to the esp. I had managed to make them work, but then suddenly esp has stopped connecting to the server. I have spent quite some time trying to figure out what happened but I don't think I have changed anything. One day they all worked together, the next they didn't.
This is the main of my java code and I believe it works, even though it's probably not ideal (apart from this there are a couple of functions to make a small GUI and to do some actions):
createGUI();
//looking for the arduino port, to get data from it
SerialPort comPort = findArduinoPort();
if (comPort != null) {
System.out.println("Arduino port found: " + comPort.getSystemPortName());
} else {
System.out.println("Arduino port not found");
System.exit(0);
}
comPort.openPort();
comPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_SEMI_BLOCKING, 0, 0);
InputStream inComPort = comPort.getInputStream();
ServerSocket listener = new ServerSocket(8020);
char lastRead;
String data = new String("0");
try{
while(true){
Thread.sleep(0);
if(myStatus == status.ON) {
//read data from aduino serial
if (inComPort.available() > 0) {
data = "";
while (true) {
lastRead = (char)inComPort.read();
if (lastRead == '\r') {
lastRead = (char)inComPort.read();
break;
} else {
data += lastRead;
}
}
}
System.out.println("Waiting for client");
//from my understanding the next line waits for the client to connect
Socket socket = listener.accept();
socket.setKeepAlive(true);
System.out.println("Client Connected");
try{
//i read data from the client, to make sure it's ready to receive
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("Client response: " + in.readLine());
//I send the data to esp8266
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
System.out.println("Sending Message: " + data);
out.write(data);
out.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
socket.close();
}
}
}
} finally {
try {
inComPort.close();
} catch (Exception e) {
e.printStackTrace();
}
comPort.closePort();
listener.close();
}
}
After writing to console "Waiting for client" it waits for a client to connect (and to my understanding it works fine). The problem comes with the code in esp8266
#include <ESP8266WiFi.h>
#include <LiquidCrystal.h>
//wifi data
#define NAME "i_put_my_wifi_here"
#define PASSWORD "i_put_my_wifi_pw_here"
String host = "i_put_my_computer_ip_here";
const int port = 8020;
WiFiClient client;
//lcd display to write the data to
LiquidCrystal lcd(D2, D3, D5, D6, D7, D8);
void setup() {
Serial.begin(115200);
//lcd setup
lcd.begin(16, 2);
lcd.print("Puntamenti:");
lcd.setCursor(0, 1);
lcd.print("0");
WiFi.mode(WIFI_STA);
WiFi.begin(NAME, PASSWORD);
Serial.print("\nConnecting to wifi");
while(WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("Connected\n");
}
void loop() {
//i try to conect to the server
if (client.connect(host, port))
{
Serial.print("Connected to host: ");
Serial.println(host);
//i tell the server i'm ready for data
client.println("Connected");
Serial.print("Wating for data");
int i = 0;
while(true){
if(client.available() == 0){
Serial.print(".");
i++;
if(i >= 10){
break;
}
delay(1000);
} else {
lcd.setCursor(0, 1);
String streamData = client.readStringUntil('\n');
lcd.print(streamData);
Serial.print("\nData received: ");
Serial.println(streamData);
break;
}
}
client.stop();
} else {
Serial.println("Connection to host failed");
}
delay(1000);
}
So my problem comes with client.connect(host, port). Last time i tried the programs it worked fine. It returned true and the rest would happen. Since today, however it's always false, so esp connects to the wifi, like the computer, but then it always fails to connect to the server waiting for it. I can't understand where's the problem, and especially how it can be that it used to work well and now it doesn't anymore.

Well, this is awkward. After spending a day on this I restarted my modem and now it works fine, just like before.
Alright, thanks anyway guys

Related

Multi threaded TCP server in Java does not reply TCP Client in C

I'm trying to test a Multi threaded TCP MuxServer in Java with a TCP client coded in C. below the code of the part which manages the communication with the client:
class Echo_TCP_Thread extends Thread
{
Socket Sock_Thr;
public Echo_TCP_Thread (Socket The_Socket)
{
this.Sock_Thr = The_Socket;
}
public void run()
{
try
{
PrintWriter output = new PrintWriter(Sock_Thr.getOutputStream());
InputStreamReader input = new InputStreamReader(Sock_Thr.getInputStream());
BufferedReader binput = new BufferedReader(input);
//
System.out.println ("Test 1"); //This message is displayed
//
String temp;
while ((temp=binput.readLine()) != null)
{
//
System.out.println ("Test 2"); //This message is not displayed
//
output.print(this.getName() + " answer -> ");
output.println(temp);
output.flush();
System.out.println ("Child Server : " + Thread.currentThread()
+ " has received" + temp);
}
}
catch (Exception e)
{
return;
}
finally
{
try
{
Sock_Thr.close();
System.out.println
("Child Server " + Thread.currentThread() + " : End !!! ");
}
catch (IOException e)
{
}
}
}
}
Even if I get connectivity and the end message is displayed in the client when I finish the communication, the client doesn't receive the echo messages from the server. I have checked with the Test messages that the program is not going into the while ((temp=binput.readLine()) != null) loop, but the message Test 1 is displayed right after I get connected to the server. What should I code to correct this?

Socket server stream messages in stream are mixed

I am implementing multiplayer game with server socket mechanism.
Game is running in one loop mechanism.
Server only broadcast any message to every player connected.
Server creates thread for every connected player
Messages are JSONs and they are being sent every 100ms from client side.
Messages are being broadcasted by server and read by client without any interval.
This is server loop:
while (true) {
try {
System.out.println("LISTENING...");
Socket clientSocket = serverSocket.accept();
System.out.println("GOT CONNECTION");
PlayerThread playerThread = new PlayerThread(clientSocket);
playerThread.start();
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Exception occured on server");
break;
}
}
This is PlayerThread loop:
while (true) {
try {
String inputMessage = in.readUTF();
System.out.println("GOT: " + inputMessage);
JsonNode jsonNode = objectMapper.readTree(inputMessage);
String senderName = jsonNode.get("senderName").asText();
if (!players.contains(this)) {
playerName = senderName;
players.add(this);
}
for (PlayerThread p : players) {
p.getOut().writeUTF(inputMessage);
}
And finally listening to messages:
public void listen() {
if (connected) {
try {
if (in.available() > 0) {
String inputMessage = in.readUTF();
System.out.println("GOT MESSAGE: " + inputMessage);
handleMessages(inputMessage);
}
} catch (IOException e) {
LOGGER.log(Level.INFO, "Connection lost");
connected = false;
}
} else
LOGGER.log(Level.INFO, "Player is not connected");
}
Method above is run in main game loop. It checks if there's something in inputStream and then reads it.
This is how correct message looks like:
GOT MESSAGE: {"type":"UPDATE_STATE","content":null,"senderName":"GRACZ 52","posX":10.0,"posY":5.0}
It works ok when there are 2 players, but the more players connect the more probably is to get message like this (or similiar broken messages):
GOT MESSAGE: 0} U{"type":"UPDATE_STATE","content":null,"senderName":"GRACZ 65","posX":10.0,"posY":5.0}
or
GOT MESSAGE: {"type":"UPDATE_STATE","content":null,"senderName":"GRACZ 24","pos
There different errors in message like Y letter, half-message or multiple messages in one row. Why such thing happen? It looks like when there are more players and they write into output stream in server side, this stream is not read yet so they are appending and appending. But it doesn't explain why there are broken and most imporant, how to resolve it?
I can move reading stream to another thread because in.readUTF() locks process but I wanted to keep it synchronized in main game loop and I don't think this will help (am I wrong?)
You need to synchronize your write loop on an object that's common between all PlayerThreads so that messages don't interleave.
synchronized(/*Should be a "global" server object*/) {
for (PlayerThread p : players) {
p.getOut().writeUTF(inputMessage);
}
}

Send a string command to a socket

I am not very familiar with telnet so I would appreciate the help from any willing.
I have smart plugs which can be switch on or off through a telnet interface.
I always use telnet via command prompt to connect to the server Digi X4 connect port (via >telnet ). If I want to switch the socket on/off, I have to now type: "12 set pow=on/off" and press enter.
I would like to implement this through java using the telnet client. I am now able to connect to the port (thanks to the answers posted on this platform), but to send the command to switch devices on/off is proving difficult for me. I still have to type "12 set pow=on/off" and press enter. I would like Java to send this command.
Below is my java code. I would appreciate your assistance. Bab
public class TelnetConnection {
static TelnetClient tc = null;
public static void main(String[] a) throws Exception
{
String[] args = {"122.1222.181.45","8085"};
System.out.println("arg value: "+args);
if(args.length < 1)
{
System.err.println("Usage: Error <remote-ip> [<remote-port>]");
System.exit(1);
}
String remoteip = args[0];
int remoteport;
if (args.length > 1)
{
remoteport = (new Integer(args[1])).intValue();
}
else
{
remoteport = 7000;
}
tc = new TelnetClient();
while (true)
{
boolean end_loop = false;
try
{
tc.connect(remoteip, remoteport);
Thread reader = new Thread (new TelnetClientExample());
tc.registerNotifHandler(new TelnetClientExample());
System.out.println("TelnetClientExample");
reader.start();
OutputStream outstr = tc.getOutputStream();
PrintWriter out = new PrintWriter(outstr);
String buff = "11 set pow=on";
//int ret_read = 0;
do
{
try
{
out.print(buff);
outstr.flush();
}
catch (IOException e)
{
System.err.println("Error");
end_loop = true;
}
}
while((true) && (end_loop == false));
try
{
tc.disconnect();
}
catch (IOException e)
{
System.err.println("Error");
}
}
catch (IOException e)
{
System.err.println("Exception while connecting:" + e.getMessage());
System.exit(1);
}
}
}
}
Try tring buff = "11 set pow=on\n"; the server may need the newline to detect end-of-command.
By the way, the loop that infinitely sends that to the server looks worrisome.
You need to send a line terminator corresponding to 'and press Enter'.
The line terminator in Telnet is defined as \r\n.

Trying to get data from textfield to ouputstream for a chat program in Java

i'm working on a simple GUI chat program in Java. The goal is for the user to choose whether to host a server or to connect as a client. All of this works. The problem I'm having is letting either the client or the server chat. ideally, the user or the server can type into the textField and hit enter (or press the send button), and then the message will be sent to every client that is connected. During execution, the server runs an infinite while loop where it waits for more clients. The problem I'm having is two-fold:
1) I'm not sure if the way I'm passing the string to the inputstream is right, and 2) I don't know when I can have the server receive and then re-send the data, since it waits at server.accept().
here's the run method:
public void run()
{
conversationBox.appendText("Session Start.\n");
inputBox.requestFocus();
while (!kill)
{
if (isServer)
{
conversationBox.appendText("Server starting on port " + port + "\n");
conversationBox.appendText("Waiting for clients...\n");
startServer();
}
if (isClient)
{
conversationBox.appendText("Starting connection to host " + host + " on port " + port + "\n");
startClient();
}
}
}
here's the startClient method:
public void startClient()
{
try
{
Socket c = new Socket(host, port);
in = new Scanner(c.getInputStream());
out = new PrintWriter(c.getOutputStream());
while (true)
{
if (in.hasNext())
{
Chat.conversationBox.appendText("You Said: " + message);
out.println("Client Said: " + message);
out.flush();
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
and here's the startServer method:
public void startServer()
{
try
{
server = new ServerSocket(port);
while (true)
{
s = server.accept();
conversationBox.appendText("Client connected from " + s.getLocalAddress().getHostName() + "\n");
}
}
catch (Exception e)
{
conversationBox.appendText("An error occurred.\n");
e.printStackTrace();
isServer = false;
reEnableAll();
}
}
And finally, here's the part of actionPerformed where I get the data and (attempt) to write it to the outputstream:
if (o == sendButton || o == inputBox)
{
if(inputBox.getText() != "")
{
out.println(inputBox.getText());
inputBox.setText("");
}
}
I guess my question is: How can I rearrange my methods so that the server can wait for text from the client and then send it back to all the clients? And, how do I send the text from the client to the server?
Among the problems with this code:
You keep creating clients and servers. Surely you should only do one of each?
You are performing blocking network operations on the event thread instead of in a separate thread.
You are looping at EOS via while (true) ... if in.hasNext(). This should be while (in.hasNext()) ...
You are accepting a socket and not apparently doing anything with it. It looks like you can only handle one client at a time. You should start a new thread to handle each accepted socket.

Client to close the connection

I got a socket listener which keep listening for data. The problem now is that the client which send data will finally close the connection by itself. Based on my codes below I am wondering do I still need to perform this part of the codes where it does writeBuffer.close();?
Should I remove the final part and just put the socket closing the catch?
public void run()
{
BufferedWriter writeBuffer = null;
BufferedReader readBuffer = null;
String message="";
try {
writeBuffer = new BufferedWriter(new OutputStreamWriter(receivedSocketConn1.getOutputStream()));
readBuffer = new BufferedReader(new InputStreamReader(receivedSocketConn1.getInputStream()));
int m = 0, count=0;
int nextChar=0;
while ((nextChar=readBuffer.read()) != -1)
{
message += (char) nextChar;
if (nextChar == '#')
{
System.out.println("\n\nSending PA : "+message);
writeBuffer.write("$PA\r\n");
writeBuffer.flush();
message="";
}
}
}
catch (Exception ex)
{
System.out.println("MyError:Exception has been caught in in the main first try");
ex.printStackTrace(System.out);
}
/*finally
{
try
{
if ( writeBuffer != null )
{
writeBuffer.close();
}
else
{
System.out.println("MyError:writeBuffer is null in finally close");
}
}
catch(IOException ex)
{
ex.printStackTrace(System.out);
}
}*/
}
It's always a good idea to explicitly close the connections you're using. Think about it, it might be possible that the client never closes the connection (of course, then you'd have to implement some kind of timeout mechanism that closes the connection on the server side after a certain amount of time, but that's a different matter).
My point is - it never hurts to be careful, and manage your resources in a conservative fashion.

Categories