Java TCP socket: data transfer is slow

后端 未结 12 1937
误落风尘
误落风尘 2020-12-01 09:50

I set up a server with a ServerSocket, connect to it with a client machine. They\'re directly networked through a switch and the ping time is <1ms.

Now, I try to

相关标签:
12条回答
  • 2020-12-01 10:12

    Can you try doing this over loopback, it should then transfer the data in second.

    If it takes minutes, there is something wrong with your application. If is only slow sending data over the internet it could be you network link which is slow.

    My guess is that you have a 10 Mb/s network between your client and your server and this is why your transfer is going slowly. If this is the case, try using a DeflatoutOutputStream and an InflatorInputStream for your connection.

    0 讨论(0)
  • 2020-12-01 10:21

    Maybe you should try sending ur data in chunks(frames) instead of writing each byte seperately. And align your frames with the TCP packet size for best performance.

    0 讨论(0)
  • 2020-12-01 10:24

    Hey, I figured I'd follow up for anyone that was interested.

    Here's the bizarre moral of the story:

    NEVER USE DataInputStream/DataOutputStream and sockets!!

    If I wrap the socket in a BufferedOutputStream/BufferedInputStream, life is great. Writing to it raw is just fine.

    But wrap the socket in a DataInputStream/DataOutputStream, or even have DataOutputStream(BufferedOutputStream(sock.getOutputStream())) is EXTREMELY SLOW.

    An explanation for that would be really interesting to me. But after swapping everything in and out, this is what's up. Try it yourself if you don't believe me.

    Thanks for all the quick help, though.

    0 讨论(0)
  • 2020-12-01 10:24

    You should download a good packet sniffer. I'm a huge fan of WireShark personally and I end up using it every time I do some socket programming. Just keep in mind you've got to have the client and server running on different systems in order to pick up any packets.

    0 讨论(0)
  • 2020-12-01 10:24

    Things to try:

    • Is the CPU at 100% while the data is being sent? If so, use visualvm and do a CPU profiling to see where the time is spent
    • Use a SocketChannel from java.nio - these are generally faster since they can use native IO more easily - of course this only helps if your operation is CPU bound
    • If it's not CPU bound, there's something going wrong at the network level. Use a packet sniffer to analyze this.
    0 讨论(0)
  • 2020-12-01 10:25

    I was using PrintWriter to send data. I removed that and sent data with BufferedOutputStream.send(String.getBytes()) and got about 10x faster sending.

    0 讨论(0)
提交回复
热议问题