英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论