简体   繁体   中英

convert byte stream to string from socket in server side java

I serialized an object to bytes and send to the server side. in the server side i got the byte stream but i want to print the object/string i got from the server in order to verify i got it well

server side:

    CarServerSocket = new ServerSocket(4441);
    System.out.println("Server is ready and waiting for connection from client..\n");
    try {
        while (true) {
            carSocket = CarServerSocket.accept();
            System.out.println("Server Connected");         
            final DataInputStream bytesIR  = new DataInputStream(carSocket.getInputStream());
            bytesIRLength = bytesIR.readInt();  
                while (bytesIRLength > 0) { 
                    byte[] messageIn = new byte[bytesIRLength];
                    bytesIR.readFully(messageIn,0,messageIn.length);
                    bytesIR.readUTF();

                }
            }
    }catch(EOFException e ){
            System.out.println("\ngot all objects from client.\ndisconnecting server...");              
            CarServerSocket.close();
            carSocket.close();
        }
    }

Cliend side - serialization

objectOut.writeObject(CarList[i]); // converting object to bytes.
        objectOut.flush();
        objectInBytes = byteOut.toByteArray();
        System.out.println("Sending car object #"+i);
        dOut.writeInt(objectInBytes.length); // getting object bytes size.
        dOut.write(objectInBytes); // sending object in bytes.  

I tired to use: toString(), readUTF()... but no luck.

can anyone please advise how i solve it?

Thank you.

You can try to read data from your InputStream with some kind of InputStreamReader, something like this :

    CarServerSocket = new ServerSocket(4441);
    System.out.println("Server is ready and waiting for connection from client..\n");
    try {
        while (true) {
            carSocket = CarServerSocket.accept();
            System.out.println("Server Connected"); 
            StringBuilder yourData = new StringBuilder();
            new BufferedReader(new InputStreamReader(carSocket.getInputStream()))
                .lines().forEach(stringBuilder::append);
            System.out.println(yourData.toString());
    }catch(EOFException e ){
            System.out.println("\ngot all objects from client.\ndisconnecting server...");              
            CarServerSocket.close();
            carSocket.close();
        }
    }

You need to use ObjectInputStream to deserialize objects. Ok, so your object is entirely contained in a datagram that you've already received. You just need to turn the data buffer into an ObjectInputStream . Coding from the hip, this would be something like ...

try( ByteArrayInputStream bais = new ByteArrayInputStream(messageIn);
        ObjectInputStream ois = new ObjectInputStream(bais)) {
    Object o = ois.readObject();
}

Edit : Here is some complete code showing this working.

public class ByteStream {

    public static void main(String[] args) throws IOException {
        Server server = new Server(4441);
        new Thread(server).start();

        Client client = new Client(4441);
        new Thread(client).start();
    }
}

class Client implements Runnable {

    private final Socket socket;

    Client(int port) throws UnknownHostException, IOException {
        socket = new Socket("localhost", port);
    }

    @Override
    public void run() {
        MyObject send = new MyObject();
        send.x = 10;
        send.msg = "X = ";

        try {
            try (DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    ObjectOutputStream oos = new ObjectOutputStream(baos)) {

                oos.writeObject(send);
                oos.flush();
                byte[] objectInBytes = baos.toByteArray();
                int length = objectInBytes.length;
                System.out.println("Client: sending 'objectInBytes' length = " + length);
                dos.writeInt(length);
                dos.write(objectInBytes);
            } finally {
                socket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class Server implements Runnable {
    private final ServerSocket serverSocket;

    Server(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    @Override
    public void run() {
        try {
            try (Socket socket = serverSocket.accept();
                    DataInputStream bytesIR = new DataInputStream(socket.getInputStream())) {
                int length = bytesIR.readInt();
                byte[] messageIn = new byte[length];
                bytesIR.readFully(messageIn);
                System.out.println("Server: got datagram length = " + length);
                process(messageIn);
            } finally {
                serverSocket.close();
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private void process(byte[] messageIn) throws IOException, ClassNotFoundException {
        try (ByteArrayInputStream bais = new ByteArrayInputStream(messageIn);
                ObjectInputStream ois = new ObjectInputStream(bais)) {
            Object o = ois.readObject();
            System.out.println(o.getClass() + ": " + o);
        }
    }
}

class MyObject implements Serializable {
    private static final long serialVersionUID = -1478875967217194114L;
    double x;
    String msg;
    public String toString() { return msg + x; }
}

And the output:

Client: sending 'objectInBytes' length = 75
Server: got datagram length = 75
class MyObject: X = 10.0
objectOut.writeObject(CarList[i]); // converting object to bytes.
objectOut.flush();
objectInBytes = byteOut.toByteArray();
System.out.println("Sending car object #"+i);
dOut.writeInt(objectInBytes.length); // getting object bytes size.
dOut.write(objectInBytes); // sending object in bytes. 

All this is completely pointless. It just wastes time and space. Just use ObjectOutputStream.writeObject() directly to the socket at the sender, and ObjectInputStream.readObject() directly from the socket at the receiver.

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