我正在编写一个简单的本地客户端 - 服务器程序,应该执行以下操作:
我遇到的问题是永远不会检索“hello client1”消息,而是程序只是保持运行而不会抛出任何异常或错误。我猜它与阻塞bufferedReader的readLine方法有关,但我还没能找到问题的正确解决方案。要在本地运行程序(请参阅Main),我使用serverThread和clientThread,也许这也可能是问题的一部分。
注意:在下面的代码中,我在似乎导致问题的行上放置了注释块,其余代码运行良好:
服务器:
public class Serverside implements Runnable{
PrintStream out;
int port;
Serverside(int port){
out = new PrintStream(System.out);
this.port = port;
}
void start(){
try{
ServerSocket serverSocket = new ServerSocket(port);
Socket connSocket = serverSocket.accept();
BufferedReader clientInput = new BufferedReader(new InputStreamReader(connSocket.getInputStream()));
DataOutputStream clientOutput = new DataOutputStream(connSocket.getOutputStream());
String clientName = clientInput.readLine();
String reply = "Hello " + clientName + "\n";
//clientOutput.writeBytes(reply);
clientOutput.close();
clientInput.close();
connSocket.close();
serverSocket.close();
}catch(Exception e){
out.println("Server: An exception has been thrown: " + e.getMessage());
}
}
@Override
public void run() {
out.println("Server running");
start();
}
}
客户端:
public class ClientSide implements Runnable {
String hostname;
String clientName;
int port;
public ClientSide(String name, int port) {
hostname = "localhost";
this.port = port;
clientName = name;
}
void start(){
try{
Socket connSocket = new Socket(hostname, port);
BufferedReader serverInput = new BufferedReader(new InputStreamReader(connSocket.getInputStream()));
DataOutputStream serverOutput = new DataOutputStream(connSocket.getOutputStream());
serverOutput.writeBytes(clientName);
//String reply = serverInput.readLine();
//System.out.println("Server says: " + reply);
serverOutput.close();
serverInput.close();
connSocket.close();
}catch(Exception e){
System.out.println("Client: An exception has been thrown: " + e.getStackTrace().toString());
}
}
@Override
public void run() {
System.out.println("Client-side running");
start();
}
}
主:
public class Main {
static final int PORT = 20000;
void start() {
Serverside server = new Serverside(PORT);
ClientSide client = new ClientSide("Elias",PORT);
Thread serverThread = new Thread(server);
Thread clientThread = new Thread(client);
clientThread.start();
serverThread.start();
}
public static void main(String[] args) {
new Main().start();
}
}
答案 0 :(得分:2)
您正在阅读线路,但您没有发送线路。您需要在客户端名称中添加行终止符。