java: ObjectInputStream给出空指针异常

huangapple go评论71阅读模式
英文:

java: ObjectInputStream gives NullPointerException

问题

服务器端

ObjectOutputStream objectOutput = null;
objectOutput = new ObjectOutputStream(serverSocket.getOutputStream());

客户端

ObjectInputStream objectInput = null;
objectInput = new ObjectInputStream(clientSocket.getInputStream()); //这里有问题

服务器工作正常。但在客户端,即在objectInput = new ObjectInputStream(clientSocket.getInputStream()); 处,我得到了Exception in thread "main" java.lang.NullPointerException。出了什么问题?

英文:

Server side

ObjectOutputStream objectOutput = null;
objectOutput = new ObjectOutputStream(serverSocket.getOutputStream());

Client side

ObjectInputStream objectInput = null;
objectInput= new ObjectInputStream(clientSocket.getInputStream());//here is the problem

Server works good. but at the client side where theobjectInput= new ObjectInputStream(clientSocket.getInputStream()); is , i get Exception in thread "main" java.lang.NullPointerException
What is wrong?

答案1

得分: 0

我的猜测是在添加ObjectInputStream之前,你的socket或inputstream可能已经关闭。如果在服务器端建立连接后,socket没有存储在可以在创建它的方法之外检索的地方,很容易发生这种情况。在这种情况下,socket将会超出范围,对象将被处理,流将会关闭。

你没有发布太多的代码,但这将是我默认的猜测(在大量使用java.net.Socket时)是发生了什么。

英文:

My guess is that somehow, your socket or inputstream is closed before you add the ObjectInputStream. This could easily happen if after establishing the connection on the server side, the socket isn't stored somewhere it can be retrieved outside of the method in which you created it. In this case, the socket would be out of scope, the object will get disposed, and the stream will close.

You haven't posted very much code, but this would be my default guess (having worked a lot with java.net.Socket) as to what it going on

huangapple
  • 本文由 发表于 2020年10月27日 23:21:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/64557553.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定