通过套接字发送多个对象

时间:2014-09-18 19:11:43

标签: java sockets networking

我有以下几段代码,并且不完全了解他们的行为方式。

客户端

public class Client {

    public static void main(String[] args) throws InterruptedException {
        try {
            final Socket socket = new Socket("localhost", 3011);
            final OutputStream socketStream = socket.getOutputStream();
            for (int i = 0; i < 10; i++) {
                final byte[] message = new byte[1 * 1000 * 1000];
                socketStream.write(message);
                socketStream.flush();
                System.out.println("sent message");
            }
            socketStream.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

服务器:

public class Server {

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        final int portNumber = 3011;
        try {
            ServerSocket serverSocket = new ServerSocket(portNumber);
            System.out.println("server running on " + portNumber);
            while (true) {
                final Socket clientSocket = serverSocket.accept();
                final InputStream inputStream = clientSocket.getInputStream();
                final byte[] in = new byte[1024];
                long start = System.currentTimeMillis();
                int totalBytesRead = 0;
                int bytesRead;
                while((bytesRead = inputStream.read(in)) >= 0) {
                    totalBytesRead += bytesRead;
                }
                long duration = System.currentTimeMillis() - start;
                System.out.println("got " + totalBytesRead + " bytes from socket");
                System.out.println("took " + duration + "ms");
                final double transferRatePerSecond = totalBytesRead / (duration / 1000f);
                System.out.println("average transfer was " + transferRatePerSecond + " bytes/second");
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

现在,我希望看到的是服务器端收到的10封个人消息。我实际得到的是一条消息,似乎是客户端发送的所有10条消息的总和。例如:

got socket Socket[addr=/5.67.133.157,port=53432,localport=3011]
got 10000000 bytes from socket
took 69332ms
average transfer was 144233.546875 bytes/second

1 个答案:

答案 0 :(得分:3)

您使用套接字的方式,在您发送的每条消息之间没有内置的中断信号......它们都在同一个InputStream上,并逐字节读取。如果您希望能够区分写入,则需要使用DataInput / OutputStream或使用在消息中标记此内容的传输/对象协议(如XML或JSON)。

顺便说一句,如果您对此测试之外的套接字感兴趣,您可能需要查看我为处理Sockets / InputStreams而编写的一些实用程序。具体而言,check out ServerSocketEx and DataFetcher