客户端:
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一行)
我把你的代码放在简单的两个main函数里面是没有问题的。
异常显示你的Server在读取readUTF时发生的,说明客户端退出了而没有关闭Socket导致的。试试在Client端处理结束后关闭socket.
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。