Search code examples
javaarrayssocketsobjectinputstream

Send array via a socket using ObjectInputStream


I'm trying to send the contents of a string array via a socket and then print the array items out at the other end.

I've been trying to use ObjectInputStream but have had no luck. If I'm honest I've scoured the web but I still don't really know what I'm doing.

Client

Putting objects into the array

String[] sendServer = new String [4];

{
    sendServer[0] = txtUsername.getText();
    sendServer[1] = dateFormat.format(date);
    sendServer[2] = txtMessageOut.getText();
    sendServer[3] = "I HOPE THIS WORKS!!!";
}

The socket has been created in another method and I can out, just unsure if if this is correct?

ObjectOutputStream objectStream = new ObjectOutputStream(clientSocket.getOutputStream());
objectStream.writeObject(sendServer);

System.out.println(sendServer[0]);
System.out.println(sendServer[1]);
System.out.println(sendServer[2]);

And for the server I have no clue. I've been trying with the ObjectInputStream with no luck. The socket on the server is just called socket.

Any help or pointers would be greatly appreciated.


Solution

  • I want to give you a code snippet. Sender and reveiver use socket to communicate. Replace Request with your data structure and eliminate the code lines you don't need.

    This is sender :

    private Response doUnicastTCP(Server remoteServer, Request request) throws ServerException {
                    Socket clientSocket = null;
                    ObjectOutputStream outToServer = null;
                    ObjectInputStream inFromServer = null;
                    try {
                        if (isStarted()) {
                            request.setRequestType(RequestType.UNICAST_TCP);
                            // LOGGER.debug("Sending " + request.getRequestType() + " "
                            // + request);
                            clientSocket = new Socket(remoteServer.getHost(), remoteServer.getUnicastTCPPort());
                            clientSocket.setSoTimeout(request.getTimeout());
                            outToServer = new ObjectOutputStream(clientSocket.getOutputStream());
                            inFromServer = new ObjectInputStream(clientSocket.getInputStream());
                            outToServer.writeObject(request);
                            Response response = (Response) inFromServer.readObject();
                            // LOGGER.debug("Received " + request.getRequestType() + " "
                            // + response);
                            if (response.getReturnValue() instanceof Exception) {
                                throw new ServerException((Exception) response.getReturnValue());
                            }
                            return response;
                        } else {
                            throw new ServerNotStartedException();
                        }
                    } catch (SocketTimeoutException e) {
                        throw new ServerException("cant execute request " + request + " on server " + remoteServer + " "
                                + e.toString());
                    } catch (ClassNotFoundException | IOException e) {
                        throw new ServerException("cant execute request " + request + " on server " + remoteServer + " "
                                + e.toString());
                    } finally {
                        try {
                            if (clientSocket != null) {
                                clientSocket.close();
                            }
                        } catch (IOException e) { //
                            LOGGER.trace("socket couldn't be closed");
                        }
                    }
                }
    

    This is receiver :

    public void run() {
                Request r = null;
                try {
                    ObjectInputStream inFromClient = new ObjectInputStream(s.getInputStream());
                    ObjectOutputStream outToClient = new ObjectOutputStream(s.getOutputStream());
                    while (isStarted()) {
                        final Object receivedObject = inFromClient.readObject();
                        // LOGGER.debug("Receiving "
                        // + ((Request) receivedObject).getRequestType() + " "
                        // + receivedObject);
                        r = (Request) receivedObject;
                        processId.set(r.getProcessId());
                        Response rs = new Response();
                        rs.setRequest(r);
                        rs.setServerFrom(GoldenNodeServer.this);
                        if (getOperationBase() != null) {
                            try {
                                Object s = ReflectionUtils.callMethod(getOperationBase(), r.getMethod(), r.getParams());
                                rs.setReturnValue(s);
                            } catch (Exception e) {
                                rs.setReturnValue(e);
                            }
                            outToClient.writeObject(rs);
                        } else {
                            rs.setReturnValue(new NoClientProxySetException());
                        }
                    }
                } catch (EOFException e) {
                    // LOGGER.trace("eof occured");
                } catch (SocketException e) {
                    if (e.toString().contains("Socket closed") || e.toString().contains("Connection reset")
                            || e.toString().contains("Broken pipe")) {
                    } else {
                        stop();
                        LOGGER.error("Error occured" + (r == null ? "" : " while processing " + r) + " ", e.toString());
                    }
                } catch (IOException | ClassNotFoundException e) {
                    stop();
                    LOGGER.error("Error occured" + (r == null ? "" : " while processing " + r) + " ", e.toString());
                } finally {
                    tcpProcessors.remove(this);
                }
            }