1 回答

TA貢獻(xiàn)1794條經(jīng)驗(yàn) 獲得超8個(gè)贊
您需要將閱讀器移入 while 循環(huán)。因?yàn)檫@是服務(wù)器等待讀取客戶端輸入的地方。
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();
}
}
然后更改客戶端:
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();
}
}
添加回答
舉報(bào)