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();
}
}
strnever changes, so maybe putstr = bf.readLine();into your loop. You have a similar problem with the client too.