我正在使用套接字在Java中編寫我的第一個客戶端 - 服務器程序。我使用Eclipse作爲IDE。當我測試兩個程序(服務器和客戶端)之間的通信時,首先使用命令提示符運行服務器,然後在Eclipse中運行客戶端。一切正常,我可以讀取和寫入套接字,但是,當我關閉Eclipse中的客戶端程序時,服務器程序也關閉。這是爲什麼發生?服務器應該在命令提示符下自行運行,它不依賴於客戶端。爲什麼服務器在關閉客戶端時停止運行?
另外我想知道是否有任何可能我可以在Eclipse中運行這兩個程序,而不是先在命令提示符下打開服務器。
這裏是我的兩個程序代碼:
服務器:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerPrg {
public static void main(String[] args) {
System.out.println("Server is running.....");
try {
ServerSocket socketSer = new ServerSocket(4444);
Socket clientSocket = socketSer.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = (new BufferedReader (new InputStreamReader(clientSocket.getInputStream())));
BufferedReader stdIn = (new BufferedReader (new InputStreamReader(System.in)));
System.out.println("Client: " + in.readLine());
String input ;
while((input = stdIn.readLine()) != null)
{ out.println(input);
System.out.println("Client: " + in.readLine());
}
}
catch (Exception e) {System.out.println("CAN'T CREATE SERVERSOCKET. PROBABLY THE PORT IS BEING USED " + e);}
} //end main
} //end public class
客戶:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class ClientPrg {
public static void main(String[] args) {
int portNumber = 4444;
try {
Socket clientSocket = new Socket("127.0.0.1", portNumber);
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String input;
while ((input = stdIn.readLine()) != null)
{
out.println(input);
System.out.println("Server: " + in.readLine());
}
} catch(Exception e)
{
System.out.println(e);
System.out.println("CAN'T CONNECT TO THE SERVER");
}
} //end main
} // end public class
我沒有意識到這一點!第二個問題呢。謝謝! – c2J
當然。只需創建兩個運行配置文件,但下次請將您的問題限制爲「每個問題一個問題」。乾杯! –