开发者社区> 问答> 正文

关于使用socket通信,android客户端,java写的服务器,传输数据时总出现异常

客户端:

 public void run() {
 // TODO Auto-generated method stub
 try {
        s = new Socket(ip, port);

        DataOutputStream os = new DataOutputStream(s.getOutputStream());
        os.writeUTF("可以准备接收了吗?");


        ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream());
        out.writeObject(u);
        out.flush();
        out.close();

        System.out.println("用户名是:"+u.getID());


    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

服务器:

 try{
            ServerSocket ss = new ServerSocket(9999);
            System.out.println("服务器正在监听!");
            Socket s = ss.accept();
            System.out.println("建立连接!");

            DataInputStream is = new DataInputStream(s.getInputStream());
            String str = is.readUTF();
            System.out.println(str);

            ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
            User u = (User)ois.readObject();

            ois.close();

            System.out.println("用户ID :"+u.getID());


        }catch(Exception e){
            e.printStackTrace();
        }

异常:

java.net.SocketException: Connection reset
 at java.net.SocketInputStream.read(Unknown Source)
 at java.net.SocketInputStream.read(Unknown Source)
 at java.net.SocketInputStream.read(Unknown Source)
 at java.io.DataInputStream.readUnsignedShort(Unknown Source)
 at java.io.DataInputStream.readUTF(Unknown Source)
 at java.io.DataInputStream.readUTF(Unknown Source)
 at com.server.EasyServer.main(EasyServer.java:24)
 (在os.writeUTF一行)

展开
收起
爵霸 2016-03-18 11:07:55 2681 0
1 条回答
写回答
取消 提交回答
  • 我把你的代码放在简单的两个main函数里面是没有问题的。
    异常显示你的Server在读取readUTF时发生的,说明客户端退出了而没有关闭Socket导致的。试试在Client端处理结束后关闭socket.

    2019-07-17 19:06:12
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载