I'm trying to send short strings via Java client to Arduino server and vice versa. Sending data to client goes fine, but when I try to send data to arduino it cuts the string into bytes and then sends the first letter. Will the following work?
for(int i = 0; i < data.length(); i++)
Even if it can be sent as characters I want to send it in one piece, because strings are very short so there should be no problems with length.
EDIT: Alright, I read client.read()
documentation, so the problem is at arduino.
This is my java code:
public class TCP {
static Socket clientSocket;
public static void main(String args[]) throws Exception {
clientSocket = new Socket("10.10.10.57", 5000);
sendToServer("HAI THERE\n");
String msg = getFromServer();
System.out.println(msg);
close();
}
static void sendToServer(String msg) throws Exception {
//create output stream attached to socket
PrintWriter outToServer = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
//send msg to server
outToServer.print(msg + '\n');
outToServer.flush();
}
static String getFromServer() throws Exception{
//create input stream attached to socket
InputStreamReader isr = new InputStreamReader(clientSocket.getInputStream());
BufferedReader inFromServer = new BufferedReader(isr);
//read line from server
String res = inFromServer.readLine(); // if connection closes on server end, this throws java.net.SocketException
return res;
}
static void close() throws IOException{
clientSocket.close();
}
}
This code sends only one byte at the same time.It might be problem in my arduino code, since I read it with
char c = client.read()
One more thing. If there is any java master, I would like to know what to do with exceptions. How should I handle disconnected socket, failed connection to server, and so forth?