0
我編寫了一個簡單的服務器客戶端程序,當我啓動服務器和客戶端時,客戶端會收到它發回服務器的消息並自行終止。但是,當我啓動另一個客戶端時,它不會收到消息。爲什麼? 非常感謝!Java爲什麼服務器不響應第二個客戶端?
第一類:客戶
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class StringClient {
public static void main(String[] args) {
Socket socket = null;
try{
socket = new Socket("localhost", 3141);
OutputStream raus = socket.getOutputStream();
PrintStream ps = new PrintStream(raus, true);
System.out.println("1");
ps.println("Hello World!");
ps.println("Hello Universe!");
InputStream rein = socket.getInputStream();
System.out.println("verf\u00FCgbare Bytes: " + rein.available());
BufferedReader br =new BufferedReader(new InputStreamReader(rein));
System.out.println(2);
while(br.ready()){
System.out.println(br.readLine());
}
}catch(UnknownHostException e){
System.out.println("Unknown Host...");
e.printStackTrace();
} catch (IOException e) {
System.out.println("IOProbleme...");
e.printStackTrace();
}finally{
if(socket != null){
try{
socket.close();
System.out.println("Socket geschlossen...");
}catch(IOException e){
System.out.println("Fehler beim Schließen des Sockets!");
e.printStackTrace();
}
}
}
}
}
第二類:服務器
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class StringServer {
private final ServerSocket server;
public StringServer(int port) throws IOException {
server = new ServerSocket(port);
}
private void connect(){
while(true){
Socket socket = null;
try{
socket = server.accept();
reinRaus(socket);
}catch(IOException e){
e.printStackTrace();
}finally{
if(socket != null){
try{
socket.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
}
}
private void reinRaus(Socket socket) throws IOException{
BufferedReader rein = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream raus = new PrintStream(socket.getOutputStream());
String s;
while(rein.ready()){
s = rein.readLine();
raus.println(s);
}
}
public static void main(String[] args) throws IOException {
StringServer server = new StringServer(3141);
server.connect();
}
}
@davidbox您對'就緒()'真正的重新調整時,它是不是在你的答案被刪除要求完成廢話。請不要重複。 – EJP