Reputation:
In server, I have send a byte array to client through Java socket
byte[] message = ... ;
DataOutputStream dout = new DataOutputStream(client.getOutputStream());
dout.write(message);
How can I receive this byte array from client?
Upvotes: 32
Views: 164967
Reputation: 1337
Try this, it's working for me.
Sender:
byte[] message = ...
Socket socket = ...
DataOutputStream dOut = new DataOutputStream(socket.getOutputStream());
dOut.writeInt(message.length); // write length of the message
dOut.write(message); // write the message
Receiver:
Socket socket = ...
DataInputStream dIn = new DataInputStream(socket.getInputStream());
int length = dIn.readInt(); // read length of incoming message
if(length>0) {
byte[] message = new byte[length];
dIn.readFully(message, 0, message.length); // read the message
}
Upvotes: 74
Reputation: 10423
You need to either have the message be a fixed size, or you need to send the size or you need to use some separator characters.
This is the easiest case for a known size (100 bytes):
in = new DataInputStream(server.getInputStream());
byte[] message = new byte[100]; // the well known size
in.readFully(message);
In this case DataInputStream
makes sense as it offers readFully()
. If you don't use it, you need to loop yourself until the expected number of bytes is read.
Upvotes: 1
Reputation: 272237
There is a JDK socket tutorial here, which covers both the server and client end. That looks exactly like what you want.
(from that tutorial) This sets up to read from an echo server:
echoSocket = new Socket("taranis", 7);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
taking a stream of bytes and converts to strings via the reader and using a default encoding (not advisable, normally).
Error handling and closing sockets/streams omitted from the above, but check the tutorial.
Upvotes: 2
Reputation: 83846
First, do not use DataOutputStream
unless it’s really necessary. Second:
Socket socket = new Socket("host", port);
OutputStream socketOutputStream = socket.getOutputStream();
socketOutputStream.write(message);
Of course this lacks any error checking but this should get you going. The JDK API Javadoc is your friend and can help you a lot.
Upvotes: 11