【发布时间】:2012-09-10 14:22:11
【问题描述】:
我想在客户连接后向他发送响应
这里是sn-p的代码
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();
}
感谢您的帮助
【问题讨论】:
-
程序在调试器中逐行运行时会阻塞在哪里?
-
@Philipp 它在“int read =in.read(reception);”处阻塞
标签: java sockets outputstream