[英]send response to a client from a server
我想在客戶端連接后向其發送回復
這是代碼片段
try {
while (true)
{
in = socket.getInputStream();
out = socket.getOutputStream();
byte[] reception = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int read = in.read(reception);
String bufferServer = "Buffer Server ";
baos.write(reception, 0, read);
reception = baos.toByteArray();
String chaine = new String(reception, "Cp1252");
System.out.println("Reception from client : " + chaine);
byte[] bufferServeurToClient = bufferServer.getBytes();
out.write(bufferServeurToClient); // send to client
out.flush();
}
}
客戶端可以發送多個請求,這就是為什么我使用while(true)來監聽請求直到客戶端斷開連接的原因。
問題是我沒有從客戶端的服務器收到任何信息。 如果我刪除while(true),它會起作用,並且我會在客戶端收到變量“ bufferServeurToClient”
編輯:現在可以工作的客戶端,但是當我打印響應時,我的字符串后面有很多奇怪的字符(方形),為什么?
String ip = InetAddress.getLocalHost ().getHostAddress ();
Socket socket = new Socket(ip, port);
System.out.println("SOCKET = " + socket);
InputStream in = socket.getInputStream();
BufferedInputStream bis = new BufferedInputStream(in);
OutputStream out = socket.getOutputStream();
BufferedOutputStream bos=new BufferedOutputStream(out);
String bufferClient="Buffer Client ";
byte[] bufferClientToServer= bufferClient.getBytes();
out.write(bufferClientToServer);
byte[] reception = new byte[1024] ;
int read;
while ((read = bis.read(reception)) != -1){
String chaine = new String( reception , "Cp1252" );
System.out.println("Reception from server: " + chaine);
}
bis.close();
bos.close();
}
謝謝您的幫助
客戶端可以發送多個請求,這就是為什么我使用while(true)來監聽請求直到客戶端斷開連接的原因。
如果客戶端可以發送多個請求,則需要一種區分它們以及響應之間的方式。 當前,您只是假設一個read
調用即可完成此工作:
int read =in.read(reception);
那可以讀取一個請求的一部分 ,或者可能讀取多個請求。 解決此問題的常用方法是使用某種定界符(例如,每個文本行一個請求)或使用長度前綴,其中(例如)每個請求或響應的前四個字節表示有多少數據。
現在您還沒有顯示出客戶端的外觀-但我的猜測是您實際上是在等待服務器關閉連接,當然, while(true)
循環存在時,您將永遠不會這樣做。 這是您需要修改的另一段代碼。
它毫無價值,如果您發送多個請求,它們很可能會被讀取為單個請求。 這是因為流沒有消息的概念,因此,如果您寫入許多字節,則可以以任何方式讀取它們。 例如一次一次或一次全部。
無論如何,您至少應該得到一個答復。
在打印任何內容之前,您一直在客戶端讀取EOS,並且服務器永遠不會關閉連接,因此沒有EOS。
您不需要所有這些ByteArrayOutputStreams。 仔細看一下您的代碼,您會發現它們可以完全消除。 這也將解決EOS問題。
如果read()返回-1,則服務器應關閉套接字。
看一下本教程文檔: http : //docs.oracle.com/javase/tutorial/networking/sockets/readingWriting.html這可能對您有幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.