服务器监听客户端并响应,从服务器向客户端发送响应

我想在连接后向客户端发送响应

这是代码片段

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)它会起作用,并且我在客户端收到变量“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();}

感谢您的帮助

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值