我需要構建一個應用程序,其中有四臺服務器在運行,一臺客戶機向這些服務器發送一些軟件包,但這些服務器必須始終保持運行,以便從客戶端(發件人)接收一些內容。 所以我創建了兩個類,客戶端和服務器:如何使用套接字創建服務器和客戶端?
public class Server {
public Event receive(int port) {
Evento event = null;
try {
ServerSocket ss = new ServerSocket(port);
Socket s = ss.accept();
InputStream is = s.getInputStream();
ObjectInputStream ois = new ObjectInputStream(is);
evento = (Evento) ois.readObject();
is.close();
s.close();
ss.close();
}catch(Exception e){
System.out.println(e);
}
return event;
}
}
public class Client {
public void send(Event event, int port) {
try {
Socket s = new Socket("localhost", 2002);
OutputStream os = s.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(event);
oos.close();
os.close();
s.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
但正如我所說,我需要這些服務器保持運行的時間,如果我考過一次,這是確定的,但兩次或兩次以上,不。 我怎麼能這樣做?
你的意思了一會兒一個線程? –
用於讀取阻塞連接的線程。它可以包含while循環。 –