print multiple lines using sockets in java - java

I'm creating a simple client-server to use with my Raspberry Pi.
What I'm trying to accomplish is to send "ACKTEMP" for example to the Server using my Client. The servers then calls the serial port (which is my STM32 Nucleo Board btw) with this message I get the temperature back using the serial communication and after that it sends it back to the Client.
My question is, the Nucleo board returns some strings like (TEMP: xx) this works fine until I start sending multiple strings back at once ex. if I send ACKTEMP and want to receive (TEMP: xx ) and "Temperature OK", doing this I only get the first line which is (TEMP: xx ).
So it seems that somewhere in my code I need to change something so it prints out all the lines instead of just one and then stop. Please don't get angry at me if my programming isn't that great I'm a student and trying to understand everything.
public class Client {
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
public static void main(String[] args) throws IOException {
String sentence;
String messageFromServer;
while(true)
{
BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
try (Socket clientSocket = new Socket("192.168.0.135", 6789)) {
PrintWriter outToServer = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.println(sentence + '\n');
messageFromServer = inFromServer.readLine();
System.out.println("FROM SERVER: " + messageFromServer);
clientSocket.close();
}
}
}
}
public class Server {
private static SerialPort serialPort;
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
public static void main(String[] args) throws IOException {
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(6789);
serialPort = new SerialPort("/dev/ttyACM0");
while(true)
{
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
PrintWriter outToClient = new PrintWriter(connectionSocket.getOutputStream(), true);
clientSentence = inFromClient.readLine();
try{
//opening port
serialPort.openPort();
serialPort.setParams(
SerialPort.BAUDRATE_115200,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
//Write string to port
serialPort.writeString(clientSentence + "\n");
System.out.println("String wrote to port, waiting for response..");
try {
Thread.sleep(10); //1000 milliseconds is one second.
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
String buffer = serialPort.readString();
outToClient.println(buffer + '\n');
serialPort.closePort();//Close serial port
}
catch(SerialPortException ex){
System.out.println("Error writing data to port: " + ex);
}
}
// TODO code application logic here
}
}

I used the following to kinda solve this problem. But if someone has a better solution it is very welcome!
What I did is for every string I want a new line, I put a "~" sign in front of the string in my Nucleo STM32 program.
String strArray[] = messageFromServer.split("~");
System.out.println("FROM SERVER: " + strArray[0]);
for(int i = 1; i < strArray.length; ++i)
{
if(messageFromServer.indexOf('~') >= 0)
{
System.out.println("FROM SERVER: " + strArray[i]);
}
}

Related

Java TCP client/server sockets

I am working on a problem that will create a TCP server and client using sockets. For the client code, my objective is to repeatedly prompt the user to enter a sentence S, send the sentence S to the server, receive the response from the server, and display the message received and the round trip time expressed in milliseconds. On the server, my objective is to create a TCP server socket, wait for a client to connect, receive a message, display it with the IP address and port # of the client, capitalize the message, display the message, and echo back the "capitalized" message.
I am trying to use a while (!(input.equals("done"){ ...do something }, however, whatever I do is getting stuck in an infinite loop. I hope its something simple I am just overlooking, but I don't see it.
TCPServer.java
import java.net.*;
import java.io.*;
public class myFirstTCPServer {
public static void main(String[] args) throws IOException {
int servPort = 4999;
ServerSocket Sy = new ServerSocket(servPort);
Socket servSocket = Sy.accept();
InputStreamReader in = new InputStreamReader(servSocket.getInputStream());
BufferedReader bf = new BufferedReader(in);
String str = bf.readLine();
while (!(str.equals("done"))){
System.out.println("client connected");
InetAddress address = InetAddress.getLocalHost();
String ip = address.getHostAddress();
System.out.println("IP: " + ip);
System.out.println("Port: " + servPort);
System.out.println("Message from client: " + str.toUpperCase());
PrintWriter pr = new PrintWriter(servSocket.getOutputStream());
pr.println(str);
pr.flush();
}
servSocket.close();
}
}
TCPClient.java
import java.net.*;
import java.io.*;
import java.util.Scanner;
public class myFirstTCPClient {
public static void main(String[] args) throws IOException {
String S;
Scanner input = new Scanner(System.in);
System.out.println("Enter a sentence");
S = input.nextLine();
Socket clntSocket = new Socket(InetAddress.getLocalHost(), 4999);
while (!(S.equals("done"))){
double sent = System.nanoTime();
PrintWriter pr = new PrintWriter(clntSocket.getOutputStream());
pr.println(S);
pr.flush();
InputStreamReader in = new InputStreamReader(clntSocket.getInputStream());
BufferedReader bf = new BufferedReader(in);
String str = bf.readLine();
System.out.println("Message from server: " + str);
double received = System.nanoTime();
double total = received - sent;
System.out.println("Round Trip Time: " + (total/1000000.0));
}
clntSocket.close();
}
}
you need to move reader into the while loop. Because this is where server waits for reading clients input.
public class myFirstTCPServer {
public static void main(String[] args) throws IOException {
int servPort = 4999;
ServerSocket Sy = new ServerSocket(servPort);
Socket servSocket = Sy.accept();
System.out.println("client connected");
InputStreamReader in = new InputStreamReader(servSocket.getInputStream());
BufferedReader bf = new BufferedReader(in);
String str ="";
while (true)){
str = bf.readLine();
if(str.equals("done")) break;
InetAddress address = servSocket.getInetAddress();
String ip = address.getHostAddress();
System.out.println("IP: " + ip);
System.out.println("Port: " + servPort);
System.out.println("Message from client: " + str);
PrintWriter pr = new PrintWriter(servSocket.getOutputStream());
pr.println(str.toUpperCase());
pr.flush();
}
servSocket.close();
}
}
And then change client side:
public class myFirstTCPClient {
public static void main(String[] args) throws IOException {
String S="";
Scanner input = new Scanner(System.in);
// you need to provide your server ip/domain
// InetAddress.getLocalHost() , still works but only works when
// your client is in the same machine.
Socket clntSocket = new Socket("127.0.0.1", 4999);
while (!(S.equals("done"))){
System.out.println("Enter a sentence");
S = input.nextLine();
double sent = System.nanoTime();
PrintWriter pr = new PrintWriter(clntSocket.getOutputStream());
pr.println(S);
pr.flush();
InputStreamReader in = new InputStreamReader(clntSocket.getInputStream());
BufferedReader bf = new BufferedReader(in);
String str = bf.readLine();
System.out.println("Message from server: " + str);
double received = System.nanoTime();
double total = received - sent;
System.out.println("Round Trip Time: " + (total/1000000.0));
}
clntSocket.close();
}
}

Why server created using java socket doesn't not print data send from client (it dislays if client terminate)?

In example below I created one server which will only print whatever client is writing in a socket. But I am not getting output as client enter data. If client terminate then I can see all the data client inserted in outputstream. I am taking input from console at client and then write that data to server socket.
Server code:
public class server {
public static void main(String[] args) throws Exception {
System.out.println("waiting");
ServerSocket s = new ServerSocket(9999);
Socket stemp = s.accept();
System.out.println("read comp");
InputStream is = stemp.getInputStream();
InputStreamReader ir = new InputStreamReader(is);
BufferedReader br = new BufferedReader(ir);
while(true)
{
String str = br.readLine();
if(str!=null)
{
System.out.println(str);
}
if(str.contains("exit"))
{
break;
}
}
stemp.close();
ir.close();
is.close();
br.close();
}
}
Client code:
public class client {
public static void main(String[] args) throws Exception {
String ip ="127.0.0.1";
int port = 9999;
Socket s1 = new Socket(ip, port);
OutputStream os = s1.getOutputStream();
OutputStreamWriter ow = new OutputStreamWriter(os);
BufferedWriter pw = new BufferedWriter(ow);
pw.write("I am ready");
Scanner s = new Scanner(System.in);
String str = s.nextLine();
System.out.println(str);
while(!str.contains("exit"))
{
pw.write(str);
pw.flush();
str = s.nextLine();
}
pw.close();
os.close();
ow.close();
s1.close();
}
}
In server, br.readLine(); is used, waiting for end-of-line.
In client, you have to send the eol in pw.write( str + '\n' );.

Communication between Java programs

I'm trying to learn how to do deal with networks in Java 8, and I'm trying to make a client program communicate with a server one. The client is asked a string, which is sent to the server, and the server sends it back in upper characters.
I can't get my server part to work, it simply won't write anything except the fact that the connection is made. Could someone explain what's wrong with my code ?
Server :
public static void main(String[] args) throws IOException {
int listenPort = 9000;
ServerSocket listenSocket = new ServerSocket(listenPort);
Socket socket = listenSocket.accept();
System.out.println("Connexion réussie !");
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
BufferedReader buffer = new BufferedReader(new InputStreamReader(inputStream));
DataOutputStream output = new DataOutputStream(outputStream);
String line = null;
System.out.println("test : " + buffer.readLine());
while((line = buffer.readLine()) != null) {
System.out.println("Message reçu : " + line);
System.out.println("Message envoyé : " + line.toUpperCase());
output.writeUTF(line.toUpperCase());
if(line.equals("stop")) {
socket.close();
listenSocket.close();
}
}
}
Client side :
public static void main(String[] args) throws IOException, UnknownHostException {
Socket socket = new Socket("127.0.0.1", 9000);
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
DataInputStream input = new DataInputStream(inputStream);
DataOutputStream output = new DataOutputStream(outputStream);
BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));
String line = null;
while((line = buffer.readLine()) != null) {
System.out.println("Message envoyé : " + line);
output.writeChars(line);
System.out.println("Message reçu : " + input.readUTF());
if(line.equals("stop")) {
break;
}
}
socket.close();
}
Inside your client method, you call output.writeChars(line) inside the while loop, this means that you send something to the server after the server send something to you.
Change your client code as follows:
String line = "What a wonderful line";
System.out.println("Message envoyé : " + line);
output.writeChars(line);
while((line = buffer.readLine()) != null) {
System.out.println("Message reçu : " + input.readUTF());
}

a client/server program using java won't work

I'm trying to create a client/server program with java.
when the client connect to the server, the server will show him a message to enter the first value when the user write the first value the server sends him a message to write the sencd value when the user write the second value the server will show him a list of operations ans wait until the client write the number of the operation and then the server will send him the result of this operation.
When I write the program's code and run the server and then the client, it doesn't do any thing the server is blocked from doing anything, also the client.
this is the code I tried :
for the client :
import java.net.*;
import java.util.Scanner;
import java.io.*;
public class Client {
final static String ADRSS = "localhost";
final static int PORT = 1234;
static Socket s = null;
public static void main(String[] args) {
try{
Scanner cn = new Scanner(System.in);
s = new Socket(ADRSS, PORT);
PrintWriter out = new PrintWriter(s.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
in.readLine();
out.println(cn.nextLine());
out.flush();
in.readLine();
out.println(cn.nextLine());
out.flush();
in.readLine();
out.println(cn.nextLine());
out.flush();
System.out.println("Res = " + in.readLine());
out.flush();
}
catch(IOException e){e.printStackTrace();
}
}
}
for the server:
import java.net.*;
import java.io.*;
public class Server {
final static int PORT = 1234;
private static ServerSocket server;
public static void main(String[] args) {
Socket s = null;
try {
server = new ServerSocket(PORT);
s = server.accept();
PrintWriter out = new PrintWriter(s.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
out.println("Donner le premier nombre : ");
out.flush();
double n1 = Double.parseDouble(in.readLine());
out.println("Donner le deuxiéme nombre : ");
out.flush();
double n2 = Double.parseDouble(in.readLine());
out.println("Donner l'op : ");
out.flush();
String choix = in.readLine();
String res = null;
switch(choix){
case "1" :
res = String.valueOf(n1 + n2);
break;
case "2" :
res = String.valueOf(n1 - n2);
break;
case "3" :
res = String.valueOf(n1 * n2);
break;
case "4" :
res = (n2 == 0) ? "Impossible d'éfectuer l'op" : String.valueOf(n1 / n2);
break;
default :
res = "erreur";
}
out.println(res);
out.flush();
}catch(IOException e) {
e.printStackTrace();
}finally{
try{
s.close();
}catch(IOException e){e.printStackTrace();}
}
}
}
PrintWriter doesn't flush output after you use regular print (refer to documentation of PrintWriter). You'd have to flush it manually. However, the real reason is your client waits for a line with newline, which never happens. Changing to out.println on the server side should make this running, also covering the flushes.
first, after every print in the server, add
out.flush();
second, you are asking for nextLine() but printing without \n ,
either add \n to end of each string or use out.println

java : string index out of range

I'm trying to learn how to use sockets , I wrote a small echo server . I run the code on eclipse , then I go to command prompt and telnet to the port , it should echo back , but instead it gives me this error :
Exception in thread "Thread-0" java.lang.StringIndexOutOfBoundsException: String index out of range: 20
at java.lang.String.getChars(Unknown Source)
at java.io.BufferedWriter.write(Unknown Source)
at echoserver.run(echoserver.java:40)
here is my code :
public final class echoserver extends Thread {
private static final int PORT = 8889;
public static void main(String args[]){
echoserver Echoserver = new echoserver();
if (Echoserver != null){
Echoserver.start();
}
}
public void run (){
try {
ServerSocket server = new ServerSocket(PORT , 1);
while (true) {
Socket client =server.accept();
System.out.println("Client connected");
while (true){
BufferedReader reader =
new BufferedReader(new InputStreamReader(
client.getInputStream()));
System.out.println("Read from client");
String textLine = reader.readLine() + "\n";
if (textLine.equalsIgnoreCase("Exit\n")){
System.out.println("exit invoked, closing client");
break;
}
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(
client.getOutputStream()));
System.out.println("Echo input to client");
writer.write("echo from server:"
+ textLine, 0 , textLine.length() + 18);
writer.flush();
}
client.close();
}
} catch(IOException e){
System.err.println(e);
}
}
}
how can I fix this error ?
This is the problem:
writer.write("echo from server:" + textLine, 0 , textLine.length() + 18);
Your "extra text" is actually 17 characters, not 18. You don't need to specify the offset and length though - you can just use:
writer.write("echo from server:" + textLine);

Categories

Resources