我想在连接后向客户端发送响应
这是代码片段
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();
}
谢谢您的帮助