I want to send multiple packets separately with using tcp socket in Java. Here's my code.
try {
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
String[] array = new String[4];
array[0] = "stack";
array[1] = "over";
array[2] = "flow";
array[3] = "coding";
for (int i = 0; i < array.length; i++) {
out.write(array[i].getBytes()); //send packet
}
} catch (IOException e) {
throw new RuntimeException(e);
}
I take all data in one packet right now. Here is the received packet's terminal output:
Incoming Transmission => stackoverflowcoding
That's what i want:
Incoming Transmission => stack
Incoming Transmission => over
Incoming Transmission => flow
Incoming Transmission => coding
How can i receive data as 4 packets separately?
Why do i want this ? Because in my client there's an event that listens the coming tcp packages. This event must be triggered for each elements of array separately.
DataOutputStream? You are not actually using it as itswrite(byte[])method directly uses thewrite(byte[])method of the output stream it wraps, which seems to suggest you're cargo-culting here.