今天写socket数据相互通信的时候,碰到一个及其蛋疼的错误。单向传输数据的时候server与client是没有问题的,但是两个都有输入输出操作的时候就出现了这个问题 java.net.SocketException: Socket is closed:

下面附代码:
Server:

        StringBuffer result = new StringBuffer("");
        int port = 9090;
        //定义一个ServerSocket监听在端口9090上
        ServerSocket server = null;

        while(true){//注意while放在哪

            try {

                server = new ServerSocket(port);
                //server尝试接收其他Socket的连接请求,server的accept方法是阻塞式的
                Socket client = server.accept();
                server.setSoTimeout(20*1000);
                System.out.println("client connected!");

                //接收消息
                Reader read = new InputStreamReader(client.getInputStream());
                BufferedReader bufferReader = new BufferedReader(read);
                String readLine = "";
                //bufferReader.readLine()用一次读一行,前面用过再用就是下一行
                while((readLine = bufferReader.readLine()) != null){
                    result.append(readLine);
                }
                bufferReader.close;
                System.out.println("from client: " + result.toString());  

                //boolean isConnected = socket.isConnected() && !socket.isClosed();

                //读完后写一句
                OutputStream os = client.getOutputStream();//这一行会报socket关闭的错误
                DataOutputStream out = new DataOutputStream(os);
                out.writeBytes("Hello Client,I'm Server!");
                System.out.println("sent mesg");

                out.flush();//清空缓存
                out.close();//关闭
                client.close();  

            } catch (IOException e) {
                e.printStackTrace();
            } finally {//这里socket.close最好放在finally里
                try
                {
                    if(server != null){
                        server.close();
                    }
                }catch(IOException e){
                    e.printStackTrace();
                }
            }   

    }         
Client: 
        StringBuffer result = new StringBuffer("") ;
        String host = "192.168.0.88";
        int port = 9090;
        Socket client = null;

        try
        {
             System.out.println("Connecting to " + host + " on port " + port);
             client = new Socket(host, port);
             client.setSoTimeout(20*1000);
             System.out.println("Just connected to " + client.getRemoteSocketAddress());
                     //发送消息
             OutputStream os = client.getOutputStream();
             DataOutputStream out = new DataOutputStream(os);
             out.writeBytes("Hello Server!");
             System.out.println("sent mesg");
             out.flush();//清空缓存
             out.close();//关闭
//接收消息
             Reader read = new InputStreamReader(client.getInputStream());//同样这里会报错
             BufferedReader bufferReader = new BufferedReader(read);
             String readLine = "";
             while((readLine = bufferReader.readLine()) != null){
                 result.append(readLine);
             }
             System.out.println("from Server: " + result.toString());
             bufferReader.close;

          }catch(IOException e){
             e.printStackTrace();
          } finally {
                try
                {
                    if(client != null){
                        client.close();
                    }
                }catch(IOException e){
                    e.printStackTrace();
                }
          }
找了很久终于找到 bufferReader.close()与out.close()关闭会直接导致sockect.close()故只进行输入输出中的一个之后就出现java.net.SocketException: Socket is closed:错误,可能是因为用到了socket.getOutputStream(),socket.getInputStream()的缘故。

这里将out.close()与bufferReader.close()兑换成client.shutdownOutput()与client.shutdownInput();之后就不会出现Socket直接被关闭的问题了。

Socket.close()->输入输出流都被关闭->有时候希望仅关闭输入流或输出流之一->Socket半关闭方法->shutdownInput():仅关闭输入流shutdownOutput():仅关闭输出流

上述问题中如果把bufferReader.close()与out.close()放在最后,就会出现Server在read的时候因为Client未关闭outputstream一直傻等下去。故此种方法不可取。

java的Socket通信例子及关于java.net.SocketException: Socket is closed错误的更多相关文章

  1. Delphi和JAVA用UTF-8编码进行Socket通信例子

    最近的项目(Delphi开发),需要经常和java语言开发的系统进行数据交互(Socket通信方式),数据编码约定采用UTF-8编码. 令我无语的是:JAVA系统那边反映说,Delphi发的数据他们收 ...

  2. Socket通信客户端设计(Java)

    public class Client extends JFrame implements Runnable{ private JPanel jPanel= new JPanel(); private ...

  3. Socket通信例子

    Server端 using System; using System.Collections.Generic; using System.ComponentModel; using System.Da ...

  4. Python Socket通信例子

    一.TCP 通信 服务端 #!/usr/bin/env python # -*- coding: utf-8 -*- # server_tcp.py import socket so = socket ...

  5. windows下用c实现Socket通信

    原文:windows下用c实现Socket通信 原本以为c是跨平台,所以,c在windows下和linux下的程序应该是类似于Java,什么都不用改变的,今儿才恍然大悟,他们的类库不一样啊-- 下面我 ...

  6. Android之从TCP/IP、HTTP看Socket通信

    1.概念 TCP/IP:属于传输层/网络层协议.手机能够使用联网功能是因为手机底层实现了TCP/IP协议,可以使手机终端通过无线网络建立TCP连接.TCP协议可以对上层网络提供接口,使上层网络数据的传 ...

  7. 基于TCP与UDP协议的socket通信

    基于TCP与UDP协议的socket通信 C/S架构与初识socket 在开始socket介绍之前,得先知道一个Client端/服务端架构,也就是 C/S 架构,互联网中处处充满了 C/S 架构(Cl ...

  8. JAVA基础知识之网络编程——-基于NIO的非阻塞Socket通信

    阻塞IO与非阻塞IO 通常情况下的Socket都是阻塞式的, 程序的输入输出都会让当前线程进入阻塞状态, 因此服务器需要为每一个客户端都创建一个线程. 从JAVA1.4开始引入了NIO API, NI ...

  9. JAVA基础知识之网络编程——-TCP/IP协议,socket通信,服务器客户端通信demo

    OSI模型分层 OSI模型是指国际标准化组织(ISO)提出的开放系统互连参考模型(Open System Interconnection Reference Model,OSI/RM),它将网络分为七 ...

随机推荐

  1. 配置centos 7 mysql

    http://www.cnblogs.com/starof/p/4680083.html 一.系统环境 yum update升级以后的系统版本为 [root@yl-web yl]# cat /etc/ ...

  2. iOS方法封装

    (void) setSubView:(UIView *)masterView subCCGRect:(CGRect)subCCGRect imageName:(NSString *)imageName ...

  3. Androidz之Activity概要学习

    Androidz之Activity概要学习 1.     Activity类概述 Activity(活动)是一个单独的.能获取焦点的,且能与用户交互的东西.所以我们通常在Activity类中的onCr ...

  4. iOS学习笔记:frame,bound,center, anchorPoint

    frame: View在它的Super View坐标系里的坐标 bound: 用来定义View自身坐标系和边界的Rect,Rect的原点表示View自身坐标系的原点坐标.举个例子: 一般情况下boun ...

  5. ganglia的yum插件的配置

    由于默认的centos的库是不存在ganglia的相关软件,因此要重新配置yum的库 配置yum库 安装yum优先级插件 yum install yum-priorities 安装Epel  此处是6 ...

  6. UVa 11427 (期望 DP) Expect the Expected

    设d(i, j)表示前i局每局获胜的比例均不超过p,且前i局共获胜j局的概率. d(i, j) = d(i-1, j) * (1-p) + d(i-1, j-1) * p 则只玩一天就就不再玩的概率Q ...

  7. 手动配置gradle

    最近从github倒入项目,运行的特别慢gradle配置有问题,解决方法: 1.C:\android\demo\hellocharts-android-master\gradle\wrapper 目录 ...

  8. windows安装TortoiseGit详细使用教程【基础篇】

    标签:tortoisegit 环境:win8.1 64bit 安装准备: 首先你得安装windows下的git msysgit1.9.5 安装版本控制器客户端tortoisegit  tortoise ...

  9. Java [Leetcode 94]Binary Tree Inorder Traversal

    题目描述: Given a binary tree, return the inorder traversal of its nodes' values. For example:Given bina ...

  10. Delphi or函数的用法

    function GetFlag(a: string): Integer;var I: Integer;begin Result := 0; for I := 0 to 3 - 1 do begin ...