题目是:
使用TCP协议完成一个客户端一个服务器。客户端从键盘输入读取一个字符串,发送到服务器。服务器接收客户端发送的字符串,反转之后发回客户端。客户端接收并打印。
下面是我写的代码,为啥在Client端获取不到输入的数据呢?求解
-------------------------------------------------------------------------------------
服务器端:
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
private static ServerSocket server;
public static void main(String[] args) throws Exception {
server = new ServerSocket(6000);
while (true) {
Socket client = server.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(client.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(client.getOutputStream());
String s_previous = inFromClient.readLine();
//StringBuffer s_temp = new StringBuffer(s_previous);
//String s_later = s_temp.reverse().toString();
outToClient.writeBytes(new StringBuffer(s_previous).reverse().toString());
}
}
}
-------------------------------------------------------------------------------------
客户端:
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws Exception {
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Socket client = new Socket("127.0.0.1",6000);
DataOutputStream outToServer = new DataOutputStream(client.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(client.getInputStream()));
String s_previous = inFromUser.readLine();
outToServer.writeBytes(s_previous + '\n');
String s_later = inFromServer.readLine();
System.out.println("From Server:" + s_later);
client.close();
}
}
|