[英]How to get a server to send a client a message on connection?
我正在嘗試編寫一個基本的客戶端服務器程序,以允許客戶端遍歷服務器的文件。 我希望服務器能夠在連接客戶端時將當前目錄中所有文件的列表發送到客戶端。 我將如何去做呢? 我已經創建了所有文件名的數組,並嘗試將它們發送到客戶端,它只是位於無限循環中(這意味着!),什么也不做。
嘗試讓服務器在客戶端連接時發送消息:
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
boolean found = false;
//Read the data from the input stream
for (int i=0;i < fileList.length;i++) {
outToClient.writeBytes(fileList[i].getName());
}
並讓服務器收到此消息:
//Prepare an object for reading from the input stream
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
//Read the data from the input stream
sentence = inFromServer.readLine();
但是這樣做只會使客戶端陷入無限循環,什么也不做。
請幫助?
首先,請確保您在客戶端和服務器之間進行了以下握手:
...正常通信。
發送0大小的郵件有時可能會出現問題。
因此,使用查詢響應方法似乎是准確的。
您的主要問題是您試圖將一個空字符串從客戶端發送到服務器。 空字符串將轉換為長度為0的字節數組。 實際上,您沒有在客戶端和服務器之間發送任何數據。 在這種情況下,您的服務器將繼續等待通過套接字的InputStream檢索數據。 由於服務器仍在等待,因此它不會繼續將數據發送回客戶端。 結果,當您的客戶端嘗試從服務器監聽數據時,它將無限期地等待,因為服務器永遠不會到達代碼的那部分。
如果您的目標是讓服務器僅在連接時發送數據,則有兩種選擇。
示例服務器:
ServerSocket socket = new ServerSocket(8888);
Socket cSocket = socket.accept();
PrintWriter out = null;
try {
out = new PrintWriter(new OutputStreamWriter(cSocket.getOutputStream()));
for (String file : new File(".").list()) {
out.println(file);
}
}
finally {
if (out != null) {
out.close();
}
cSocket.close();
socket.close();
}
客戶端示例:
Socket s = new Socket("localhost", 8888);
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(s.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
}
finally {
if (in != null) {
in.close();
}
s.close();
}
在我的基本服務器-客戶端TCP示例中,我提出了一種方法...當客戶端被接受時,它會收到一條歡迎消息。 因為當我從客戶端發送角色時,它給了我名字。 這是來源>> http://matrixsust.blogspot.com/2011/10/basic-tcp-server-client.html的鏈接。
希望能幫助到你。
我不認為有可能服務器無提示地向客戶端發送消息。 發送消息“ dir”並在服務器上偵聽,然后在客戶端上偵聽並回復。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.