【问题标题】:convert byte stream to string from socket in server side java将字节流从服务器端java中的套接字转换为字符串
【发布时间】:2016-07-01 14:34:16
【问题描述】:

我将一个对象序列化为字节并发送到服务器端。 在服务器端,我得到了字节流,但我想打印从服务器获取的对象/字符串,以验证我得到了它

服务器端:

    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();
        }
    }

客户端-序列化

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.  

我厌倦了使用:toString()、readUTF()...但没有运气。

谁能告诉我如何解决它?

谢谢。

【问题讨论】:

  • 您实际上可能想要使用ObjectInputStreamreadObject() 方法。当然,那么你会想写信给ObjectOutputStream ...
  • 使用'new String(messageIn)'怎么样?
  • 如果您需要有意义的帮助,您需要向我们展示对象被序列化的客户端代码。
  • 我不能使用 ObjectOutputStream,因为我必须在服务器端使用 (messageIn,0,messageIn.length)。意味着读取一个字节流并从中提取对象
  • 问题的答案仍然取决于数据的发送方式。是 (a) writeUTF() (b) 一行 (c) 其他吗,如果是,那又是什么?您关于不使用 ObjectOutputStream 的评论与您序列化对象的声明完全矛盾。是哪个?

标签: java sockets client-server inputstream


【解决方案1】:

您需要使用ObjectInputStream 来反序列化对象。好的,所以您的对象完全包含在您已经收到的数据报中。您只需要将数据缓冲区转换为ObjectInputStream。从臀部编码,这就像......

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

编辑:这里有一些完整的代码展示了它的工作原理。

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; }
}

还有输出:

Client: sending 'objectInBytes' length = 75
Server: got datagram length = 75
class MyObject: X = 10.0

【讨论】:

    【解决方案2】:
    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. 
    

    这一切都是毫无意义的。只是浪费时间和空间。只需在发送方的套接字上直接使用ObjectOutputStream.writeObject(),在接收方的套接字上直接使用ObjectInputStream.readObject()

    【讨论】:

    • 不管有什么用,写冗余代码从来没有任何意义。如果有人真的指定了这种奇怪的发送技术,就需要问他们为什么。
    【解决方案3】:

    您可以尝试使用某种 InputStreamReader 从您的 InputStream 中读取数据,如下所示:

        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();
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2019-03-18
      • 1970-01-01
      • 2017-10-05
      • 1970-01-01
      • 2011-06-12
      • 1970-01-01
      • 2015-12-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多