Socket communication between ESP32 and java local server - java

I'm trying to set a simple communication between an ESP32 as client, and a Java server running on my Windows PC.
I have this python code for the server that works:
import socket
s = socket.socket()
s.bind(('192.168.1.246', 8090 ))
s.listen(0)
while True:
client, addr = s.accept()
while True:
content = client.recv(32)
if len(content) ==0:
break
else:
print(content)
print("Closing connection")
client.close()
But my whole software is written in java, so I need to write something like that in java.
Here is my Java Code for the Server:
Thread serverThread = new Thread(new Runnable() {
#Override
public void run() {
try{
ss = new ServerSocket(8090);
s = ss.accept();
din = new DataInputStream(s.getInputStream());
dout = new DataOutputStream(s.getOutputStream());
clientMessage = (String) din.readUTF();
while(!clientMessage.equals("stop")){
clientMessage = din.readUTF();
serverMessage = "This is the message from the server";
dout.writeUTF(serverMessage);
dout.flush();
}
din.close();
s.close();
ss.close();
}catch(Exception e){
e.printStackTrace();
//System.out.println(e);
}
}
});
serverThread.start();
My Arduino code for the ESP32 is:
include <WiFi.h>
const char* ssid = "myssid";
const char* password = "mywifipass";
const uint16_t port = 8090;
const char * host = "192.168.1.246";
void setup()
{
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("...");
}
Serial.print("WiFi connected with IP: ");
Serial.println(WiFi.localIP());
}
void loop()
{
WiFiClient client;
if (!client.connect(host, port)) {
Serial.println("Connection to host failed");
delay(1000);
return;
}
Serial.println("Connected to server successful!");
client.print("Hello from ESP32!");
Serial.println("Disconnecting...");
client.stop();
delay(10000);
}
If I use python server everything works great, but if I use Java server I can establish the connection between them and I get an EOFExcepion at server line:
clientMessage = (String) din.readUTF();
readUTF() API's says:
Throws:EOFException - if this input stream reaches the end
before reading all the bytes.
So, what's going on here and how can I solve it?

I solved the issue replacing
clientMessage = (String) din.readUTF();
with:
byte[] myMessage = din.readAllBytes();
clientMessage = translate(myMessage);
where translate() function is:
private static String translate(byte[] word)
{
String translatedMessage = "";
for(int i=0; i<word.length; i++) {
translatedMessage = translatedMessage + (char) word[i];
}
return translatedMessage;
}

Related

Java - read register value by OBIS code with TCP client

I have connection to TCP server (ip,port) to which meter is connected. I'd like to read the specified data from this port because when I'm using standard read method it sends me the whole data stream which takes about 15 minutes to read. So my question: is there any method I can use to get one specified register's value using his OBIS code (1.1.1.8.0.255 - active energy taken) in java via TCP server?
import java.net.*;
import java.io.*;
public class scratch {
public static void main(String[] args) {
String hostname = "ip (hidden)";
int port = port (hidden);
try (Socket socket = new Socket(hostname, port)) {
OutputStream out = socket.getOutputStream();
InputStream input = socket.getInputStream();
InputStreamReader reader = new InputStreamReader(input);
int character;
StringBuilder data = new StringBuilder();
String test = "/?!\r\n";
byte[] req = test.getBytes();
out.write(req);
while ((character = reader.read()) != '\n') {
data.append((char) character);
}
System.out.println(data);
} catch (UnknownHostException ex) {
System.out.println("Server not found: " + ex.getMessage());
} catch (IOException ex) {
System.out.println("I/O error: " + ex.getMessage());
}
}
}
The message "test" send initiation request to meter and his respond is correct but I dont' know how to put flags (ACK STX ETX) in my request, I've tried something like this:
String test2 = (char)0x6 + "051\r\n";
byte[] req2 = test2.getBytes("ASCII");
out.write(req2);
But meter doesn't recognize it.

Send stream of Data from client program (running in VM) to server program(on Host OS) using socket programming in Java

A Client socket Program (in windows VM) generates integer from 1 to 10 as per below code
public class ClientSocket {
public static void main(String[] args)
{
try{
InetAddress inetAddress = InetAddress.getLocalHost();
String clientIP = inetAddress.getHostAddress();
System.out.println("Client IP address " + clientIP);
Integer dataSendingPort ;
dataSendingPort = 6999 ;
Socket socket = new Socket("192.168.0.32",dataSendingPort);
String WelcomeMessage = " hello server from " + clientIP ;
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
if(socket.isConnected()){
System.out.println("connection was successful");
}
else{
System.out.println("Error- connection was not successful");
}
for (int x= 0 ; x< 10 ; x++){
bufferedWriter.write(x);
bufferedWriter.flush();
}
bufferedWriter.close();
}
catch (IOException e){
System.out.println(e);
}// catch
finally{
System.out.println("closing connection");
}
} // main
} // class
My server socket program is running on Mac OS as Host Machine, whose code is shown below
public class MyServer {
public static void main(String[] args) throws Exception {
try {
// get input data by connecting to the socket
InetAddress inetAddress = InetAddress.getLocalHost();
String ServerIP = inetAddress.getHostAddress();
System.out.println("\n server IP address = " + ServerIP);
Integer ListeningPort ;
ListeningPort = 6999 ;
ServerSocket serverSocket = new ServerSocket(ListeningPort);
System.out.println("server is receiving data on port # "+ ListeningPort +"\n");
// waiting for connection form client
Socket socket = serverSocket.accept();
if(socket.isConnected()){
System.out.println("Connection was successful");
}
else {
System.out.println("connection was not successful");
}
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Integer s = 0 ;
while (( s = input.read()) >= 0){
System.out.println(input.read());
}
} //try
catch (IOException e)
{
System.out.println(e);
} // catch
} //main
} //socket class
The issue is that output I am receiving is -1 when I use while loop and receive first value i.e 0 without using a loop.
However, I was able to send a single value from client to server, but
how can I send Stream of Values from the client and print it on Server
Side.
Suggestions are most welcome
-1 means end of stream.
Closing the input or output stream of a stock closes the socket.
socket.isConnected() cannot possibly be false at the point you are testing it.
input.ready() isn't a test for end of stream, or end of message, or end of transmission, or anything useful at all really.
Don't flush inside loops.

Java Client C# Server sending issue

I am trying to set up Client-Server communication where C# is the
server side and Java is the client side. The connection is successful
and I am able to send a string from C# to Java. However, I am having
issues sending a string from Java to C#. The Server does not get any
input.
My code is the following: Server Side C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace ServerToJava
{
class Program
{
static void Main(string[] args)
{
TcpListener serverSocket = new TcpListener(5678);
int requestCount = 0;
TcpClient clientSocket = default(TcpClient);
serverSocket.Start();
Console.WriteLine(" >> Server Started");
clientSocket = serverSocket.AcceptTcpClient();
Console.WriteLine(" >> Accept connection from client");
requestCount = 0;
NetworkStream networkStream = clientSocket.GetStream();
try
{
requestCount = requestCount + 1;
string serverResponse = "Last Message from client server This is a test";
Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);
networkStream.Write(sendBytes, 0, sendBytes.Length);
Console.Write ("ReadClient Thread started");
int length = networkStream.ReadByte ();
byte[] buffer = new byte[length];
int size = networkStream.ReadByte ();
byte[] buff = new byte[size];
using (var memoryStream = new MemoryStream(buff,false)) {
using (var streamReader = new StreamReader(memoryStream, Encoding.UTF8)) {
var message = streamReader.ReadLine();
buff = Encoding.UTF8.GetBytes(message);
networkStream.Read(buffer, 0 ,buffer.Length);
Console.Write (message);
networkStream.Flush();
}
}
}
catch (Exception ex)
{
}
clientSocket.Close();
serverSocket.Stop();
Console.WriteLine(" >> exit");
Console.ReadLine();
}
}
}
Client Side Java
OutputStream out;
Socket s = new Socket("127.0.0.1", 5678);
BufferedReader input =
new BufferedReader(new InputStreamReader(s.getInputStream()));
String answer = input.readLine();
JOptionPane.showMessageDialog(null, answer);
out= s.getOutputStream();
out.write('a');
System.exit(0);
You shouldn't use new TcpListener(5678) it is Obsolete, instead use the following:
// Set the TcpListener on port 5678.
Int32 port = 5678;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
TcpListener server = new TcpListener(localAddr, port);
Source` MSDN

TCPClient - Send & Receive Response

I'm connecting to a remote TCP Listener that receives a string, and responds with a response.
Going from my Windows 8 Phone App, to a Java Jar. The Jar IS receiving the message, but the Windows 8 Phone App is not getting the response.
C# Code
outputClient.Connect (/IP ADDRESS/, /Port/);
using (Socket sock = outputClient.Client) {
sock.Send (UTF8Encoding.ASCII.GetBytes (broadcastMessage));
var response = new byte[100];
sock.Receive (response);
var str = Encoding.ASCII.GetString (response).Replace ("\0", "");
Console.WriteLine ("[RECV] {0}", str);
} <-- JAVA CODE DOESN'T GET HIT UNTIL THIS LINE IS COMPLETED
Java Code
String clientSentence;
ServerSocket socketServer = new ServerSocket(/* PORT */);
while (true)
{
Socket connectionSocket = socketServer.accept();
connectionSocket.setKeepAlive(true);
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
clientSentence = inFromClient.readLine();
BufferedWriter outToClient = new BufferedWriter(new OutputStreamWriter(connectionSocket.getOutputStream()));
if (clientSentence != null)
{
try
{
JsonObject json = new JsonParser().parse(clientSentence).getAsJsonObject();
String un = json.get("Username").toString();
String uuid = "2c9c79a096ef4d869fb1d1e07469bb41".replaceAll(
"(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})",
"$1-$2-$3-$4-$5");
var val = /* Get val */
String response = gson.toJson(val);
outToClient.write(response);
outToClient.newLine();
outToClient.flush();
}
catch (Exception ex)
{
ex.printStackTrace();
outToClient.write(response);
outToClient.newLine();
outToClient.flush();
}
}
connectionSocket.close();
}
A little more explanation: JAVA CODE DOESN'T GET HIT UNTIL THIS LINE IS COMPLETED means that the socket appears to not be sending until using (Socket sock = outputClient.Client) is no longer being used.
I fixed it by replacing the C# code with:
using (TcpClient client = new TcpClient (/IP ADDRESS/, /PORT/))
using (NetworkStream stream = client.GetStream ())
using (StreamReader reader = new StreamReader (stream))
using (StreamWriter writer = new StreamWriter (stream)) {
writer.AutoFlush = true;
foreach (string lineToSend in linesToSend) {
Console.WriteLine ("Sending to server: {0}", lineToSend);
writer.WriteLine (lineToSend);
string lineWeRead = reader.ReadLine ();
Console.WriteLine ("Received from server: {0}", lineWeRead);
Thread.Sleep (2000); // just for effect
}
Console.WriteLine ("Client is disconnecting from server");
}

PHP/Java Sockets - Strange error?

Java code:
package servermonitor;
import java.io.*;
import java.net.*;
public class CommandListener extends Thread
{
public int count = 0;
public void run()
{
try
{
ServerSocket server = new ServerSocket(4444);
while(true)
{
System.out.println("listening");
Socket client = server.accept();
System.out.println("accepted");
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
System.out.println("got reader");
String data = "";
String line;
while((line = in.readLine()) != null)
{
System.out.println("inloop");
data = data + line;
}
System.out.println("RECIEVED DATA: " + data);
in.close();
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
count++;
out.write("gotcha: " + count + "\\n");
out.flush();
}
}
catch(IOException ex)
{
System.out.println(ex.getMessage());
}
}
}
Java console (when I access the following PHP script):
listening
accepted
got reader
PHP code:
<?php
$PORT = 4444; //the port on which we are connecting to the "remote" machine
$HOST = "localhost"; //the ip of the remote machine (in this case it's the same machine)
$sock = socket_create(AF_INET, SOCK_STREAM, 0) //Creating a TCP socket
or die("error: could not create socket\n");
$succ = socket_connect($sock, $HOST, $PORT) //Connecting to to server using that socket
or die("error: could not connect to host\n");
$text = "Hello, Java!\n"; //the text we want to send to the server
socket_write($sock, $text, strlen($text) + 1) //Writing the text to the socket
or die("error: failed to write to socket\n");
$reply = socket_read($sock, 10000) //Reading the reply from socket
or die("error: failed to read from socket\n");
echo $reply;
?>
When I navigate to the PHP page, it loads forever.
Any ideas?
The Java side expects a newline in its input. You're not sending one, so readLine never finishes.
Also, readLine won't return null until the socket is closed or an exception occurs (I/O error for instance). You need to return some data as soon as you've read a line if your protocol works like that.
As it was told, you need to close socket to readLine returns null.

Categories