1
我正在寫一個簡單的本地客戶端 - 服務器程序,應做到以下幾點:客戶端服務器通信受阻於客戶端
- 客戶端發送了他的名字服務器(「客戶端1」)
- 服務器返回一個字符串說「你好客戶端1」
我遇到的問題是,「你好客戶端1」郵件永遠不會恢復,而是程序只是不斷沒有拋出任何異常或故障運行。我猜測它與阻止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();
}
}
我對Java並不熟悉,無法驗證,但可能客戶端在寫入clientName時不存在\ n。並且由於缺少\ n服務器的readline無限期地等待 – shurik
爲什麼DataOutputStream不是更友好的打印方式,就像'PrintStream'一樣? –