我在写TCP的客户端与服务端的时候
如果要服务端回送消息,那么在客户端发送完毕后要shutdownOutput,
如果没有这句代码,则不能接受服务端返回的数据,视频中说是这句代码的话服务端不知道客户端是否发送完毕,所以一直在等待,这个相信大家都自动
- //客户端
- @Test
- public void client() {
- Socket socket = null;
- OutputStream os = null;
- InputStream is = null;
- try {
- socket = new Socket(InetAddress.getByName("192.168.1.16"), 8989);
- os = socket.getOutputStream();
- //发送消息
- os.write("收到没".getBytes());
- //告诉服务端这边发送完毕
- socket.shutdownOutput();//====================没有这句下面的代码不能运行
- //建立输入流,输入服务端发来的消息
- is = socket.getInputStream();
- byte[] buf = new byte[20];
- int len= 0;
- while((len = is.read(buf))!=-1){
- System.out.println(new String(buf,0,len));
- }
- } catch (UnknownHostException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } finally {
- if (socket != null) {
- try {
- socket.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }
复制代码
但是今天看到一个不用socket.shutdownOutput(); 也能接受服务端返回的数据
- public class Demo1Client {
-
- public static void main(String[] args) throws Exception {
- Socket socket = new Socket(InetAddress.getLocalHost(), 9090);
- String data = "这个是我第一个tcp的例子";
- OutputStream out = socket.getOutputStream();
- out.write(data.getBytes());
-
- //客户端要接收服务端回送的数据
- InputStream inputStream = socket.getInputStream();
- byte[] buf = new byte[1024];
- int length =inputStream.read(buf);
- System.out.println("客户端接收到的内容是:"+ new String(buf,0,length));
- socket.close();
- }
- }
复制代码
一直没搞明白,请问这是为什么呢
|
|