how to send an array of bytes over a TCP connection (java programming)

前端 未结 9 1751
粉色の甜心
粉色の甜心 2020-12-13 14:45

Can somebody demonstrate how to send an array of bytes over a TCP connection from a sender program to a receiver program in Java.

byte[] myByteArray
<         


        
9条回答
  •  北海茫月
    2020-12-13 15:10

    I'm guessing that the question is worded incorrectly. I found this when searching for an answer to why my use of InputStream and OutputStream seemed to be setting the entire array to 0 upon encountering a byte of value 0. Do these assume that the bytes contain valid ASCII and not binary. Since the question doesn't come right out and ask this, and nobody else seems to have caught it as a possibility, I guess I'll have to satisfy my quest elsewhere.

    What I was trying to do was write a TransparentSocket class that can instantiate either a TCP (Socket/ServerSocket) or a UDP (DatagramSocket) to use the DatagramPacket transparently. It works for UDP, but not (yet) for TCP.

    Follow-up: I seem to have verified that these streams are themselves useless for binary transfers, but that they can be passed to a more programmer-friendly instantiation, e.g.,

    new DataOutputStream(socket.getOutputStream()).writeInt(5);

    ^ So much for that idea. It writes data in a "portable" way, i.e., probably ASCII, which is no help at all, especially when emulating software over which I have no control!

提交回复
热议问题