1
我正在創建一個應用程序,它需要在網絡上的多臺計算機之間來回傳輸數據。由於要發送數據的方式,客戶端計算機將運行套接字服務器,並且協調計算機將運行客戶端套接字。從套接字讀取和寫入不產生輸出?
我已經創建了簡單的類,它只是用來封裝讀寫這些套接字。然而,接收套接字並不會讀取任何內容,而只是輸出任何內容。我已確認客戶端和服務器都有連接。
在以下Server
和Client
類中,Socket
僅爲調試目的而公開。
public class Server {
public Socket client;
private DataInputStream inStr;
private PrintStream outStr;
public Server() throws UnknownHostException, IOException {this("localhost");}
public Server(String hostname) throws UnknownHostException, IOException {
client = new Socket(hostname, 23);
inStr = new DataInputStream(client.getInputStream());
outStr = new PrintStream(client.getOutputStream());
}
public void send(String data) {outStr.print(data); outStr.flush();}
public String recv() throws IOException {return inStr.readUTF();}
}
以下是我的Client
:
public class Client {
private ServerSocket serv;
public Socket servSock;
private DataInputStream inStr;
private PrintStream outStr;
public Client() throws IOException {
serv = new ServerSocket(23);
servSock = serv.accept();
inStr = new DataInputStream(servSock.getInputStream());
outStr = new PrintStream(servSock.getOutputStream());
}
public void send(String data) {outStr.print(data); outStr.flush();}
public String recv() throws IOException {return inStr.readUTF();}
}
客戶端類實例化,並且程序開始執行。然後,在一個單獨的程序,服務器實例化和啓動:
Server s = new Server(); System.out.println(s.client.isConnected());
while(true) {System.out.println(s.recv()); Thread.sleep(200);}
Client c = new Client(); System.out.println(c.servSock.isConnected());
while(true) {c.send("Hello World!"); Thread.sleep(200);}
isConnected()
回報true
的客戶端和服務器。
這可能是什麼原因造成的?我以前從來沒有必須使用套接字。
技術上並不重要,但它實際上是「接受(..)」的服務器,以及通過指定主機和端口連接到服務器的客戶端。所以,如果類名互換,這將更有意義。 – SuperSaiyan
@Thrustmaster我知道。因爲協調計算機正在運行套接字客戶端,所以它們被翻轉;所有其他客戶端等待傳入連接。 – Zyerah
@Telthien,使用'DataOutputStream'而不是'PrintStream'。我剛試過,它的工作原理。 – hiway