简体   繁体   中英

Client is not receiving Object sent by Server over ObjectStream in Java

I tried to solve the problem for quite a long time and finally decided to take help from experts. I have developed Server-client application using Socket Programming and my client is able to connect to the Server successfully. Now I am trying to send the object over the socket from server based on the request from client, my server is able to catch the request however, response(writeObject(...)) sent by server is not able to reach to the client.

Server code snippet :

ServerSocket sSocket = new ServerSocket(socketNumber);
ArrayList<LoginPassword> logIn = new ArrayList<>();
Socket cSocket = sSocket.accept();
ObjectOutputStream outputStream = new ObjectOutputStream(cSocket.getOutputStream());
outputStream.flush();
ObjectInputStream inputStream = new ObjectInputStream(cSocket.getInputStream());
LoginPassword lp1 = new LoginPassword("admin","admin");
logIn.add(lp1);
outputStream.writeObject(logIn);
outputStream.flush();

Clinet code Snippet :

Socket client = new Socket(InetAddress.getLocalHost(),socketNumber);
ArrayList<LoginPassword> myList = new ArrayList<>();
ObjectOutputStream outputStream = new ObjectOutputStream(client.getOutputStream());
outputStream.flush();
ObjectInputStream inputStream = new ObjectInputStream(client.getInputStream());
//Wait untill the data is available
myList = (ArrayList<LoginPassword>) inputStream.readObject();

In my case, clients readObject() is never called since it is not able to detect the data sent by Server.Any help please.

You must create the ObjectOutputStream first, preferably at both ends. Otherise you will get a deadlock creating the ObjectInputStream .

Alternatively I'd be curious to know what the meaning of the following comment is:

// Wait untill the data is available

If this indicates a piece of missing code that calls available() , just delete it. readObject() will block for exactly as long as necessary. There are few correct uses of available() , and this isn't one of them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM