a client/server program using java won't work - java

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

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' );.

print multiple lines using sockets in 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]);
}
}

Sending binary file over TCP from Python server to Java client

I am trying to send binary files over TCP. The server is written in Python and the client in Java.
Server:
import socket;
TCP_IP = '127.0.0.1'
TCP_PORT = 5001;
BUFFER_SIZE = 1024;
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
except:
"Can not bind server on port: "+ str(TCP_PORT) +"\n";
while 1:
print("Wait for connections!!!\n");
conn, addr = s.accept();
print("Receive a new connection!!!\n");
# presentation of client
data = conn.recv(BUFFER_SIZE);
if not data:
conn.close();
print("Lost connection!!!");
continue;
# respond to client
conn.sendall("Hello 1\n");
# receive new request
data = conn.recv(BUFFER_SIZE);
if not data:
continue;
conn.sendall("OK\n");
f = open('testImage.jpg', "rb");
dataRaw = f.read();
f.close();
fileSize = len(dataRaw); #sys.getsizeof(dataRaw);
# send file size
conn.send(str(fileSize) + "\n");
conn.send(dataRaw);
conn.sendall("OK\n");
Client
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class mainTestReceiveFile
{
public static void main(String[] args) throws Exception
{
String usr2ConnectDefault = "127.0.0.1";
int port2ConnectDefault = 5001;
Socket socket;
BufferedReader in;
PrintWriter out;
socket = new Socket(usr2ConnectDefault, port2ConnectDefault);
System.out.println("Connected to server...sending echo string");
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(),true);
// say hello to server
out.println("Hello");
// read hello from server
String readString = in.readLine();
System.out.println(readString);
out.println("ReadFile");
// verify if request is OK
readString = in.readLine();
if(readString.compareToIgnoreCase("OK") == 0)
System.out.println("Receive new file!!!");
else
{
socket.close();
return;
}
// get size of file
readString = in.readLine();
int sizeOfFile = Integer.parseInt(readString);
//InputStream is = socket.getInputStream();
byte[] fileData = new byte[sizeOfFile];
for(int i = 0; i < sizeOfFile; i++)
{
fileData[i] = (byte)in.read();
}
// save file to disk
FileOutputStream fos = new FileOutputStream("fileImage.jpg");
try
{
fos.write(fileData);
}
finally {
fos.close();
}
// verify if request is OK
readString = in.readLine();
if(readString.compareToIgnoreCase("OK") == 0)
System.out.println("New file received!!!");
else
{
socket.close();
return;
}
socket.close();
}
}
I am trying to send for example one image. In the client side, the image received has the same size (file size and number of pixels) but the data is corrupted.

double enter needed. why?

I'm facing a problem with a need to double "enter" in order for the program to proceed, can someone enlighten me?
public void run() {
try {
out.write("Enter message to encrypt: \n");
out.flush();
while (true) {
entry = in.readLine();
result = caesarCipher(entry);
out.write("The encrypted message is " + result);
out.write("\tType q to end else type another message to encrypt");
out.flush();
}
} catch (IOException e) {
System.out.println(e);
}
}
this is over at the client side
public EncryptClient() throws IOException {
Socket cSock = new Socket("LocalHost", portNumber);
Reader iRead = new InputStreamReader(cSock.getInputStream());
input = new BufferedReader(iRead);
userTerminal = new BufferedReader(new InputStreamReader(System.in));
output = new OutputStreamWriter(cSock.getOutputStream());
while (true) {
String line = input.readLine();
System.out.println(line);
line = userTerminal.readLine();
if (line.equals("q")) {
break;
}
output.write(line + "\n");
output.flush();
}
}
when my client class is connect to the server class, i will need to enter a message for encryption, but a double enter is needed to show the result. can someone enlighten me?
ReadLine will halt the control of flow.
In your code, they were two readLine
.readLine(); // (line string is overrided twice)duplicated. Remove it. You will be fine.

Categories

Resources