Send byte socket java

Sending a byte array with Java socket

I am programming an application which allows to download pdf files from a server. In my server side, I get a bytebuffer of my pdf file thanks to the pdfview library. I fill byte arrays with my byte buffer and then I send the byte arrays with a DataOutputStream. Most of the time, I get good data in my client side, but sometimes I get an array filled with random numbers and so I can’t rebuild my pdf file. I usually have the following error : «java.io.IOException: This may not be a PDF File» So When I compare received data with sent data, it is totally different. I can noticed that data in the server part are always correct Any help is appreciated

//Server side this.in = new ObjectInputStream(this.socket.getInputStream()); this.out = new DataOutputStream(this.socket.getOutputStream()); this.outObject = new ObjectOutputStream(this.socket.getOutputStream()); this.res = this.in.readObject().toString();//I read the client order(GET home page, next page. ) //I get the bytebuffer from the pdf file------ this.file = new File (name+this.numFile+".pdf"); RandomAccessFile raf; raf = new RandomAccessFile(this.file, "r"); FileChannel channel = raf.getChannel(); this.buf = channel.map(FileChannel.MapMode.READ_ONLY,0, channel.size()); //-------------------------------------------- int size = this.buf.capacity(); this.out.writeInt(size);//I send the size of my bytebuffer to the server int size_array = 1000; this.pack = new byte[size_array]; this.pack = clean_array();//I replace my variable by an array filled with zeros for(long i=0;i <(size/size_array);i++)< buf.get(this.pack); this.out.write(this.pack); this.pack = clean_array();//I replace my variable by an array filled with zeros >//I have not sent the whole bytebuffer, the last byte array could have a different size //I work out this size, I create the new bytearray and I send it--------------------- int byteLeft = size%size_array; if(byteLeft>0) < this.pack = new byte[byteLeft]; buf.get(this.pack); this.out.write(this.pack); this.pack = clean_array();//I replace my variable by an array filled with zeros >//------------------------------------------------- //Client side int size_array = 1000; pack =new byte[size_array]; pack = clean_array(); for(int i=0;i <((size/size_array));i++)< in.read(pack); buf.put(pack); pack = clean_array(); >if(size%size_array>0) < //for the last loop, the number of bytes sent by the server is not equal to 1000 //So I create a byte array with the good size pack = new byte[size%size_array]; in.read(pack); buf.put(pack); pack = clean_array(); >

Источник

Java sending and receiving file (byte[]) over sockets

I am trying to develop a very simple client / server where the client converts a file to bytes, sends it to the server, and then converts the bytes back in to a file. Currently the program just creates an empty file. I’m not a fantastic Java developer so any help much appreciated. This is the server part that receives what the client sends.

ServerSocket serverSocket = null; serverSocket = new ServerSocket(4444); Socket socket = null; socket = serverSocket.accept(); DataOutputStream out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream())); DataInputStream in = new DataInputStream(new BufferedInputStream(socket.getInputStream())); byte[] bytes = new byte[1024]; in.read(bytes); System.out.println(bytes); FileOutputStream fos = new FileOutputStream("C:\\test2.xml"); fos.write(bytes); 
Socket socket = null; DataOutputStream out = null; DataInputStream in = null; String host = "127.0.0.1"; socket = new Socket(host, 4444); out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream())); in = new DataInputStream(new BufferedInputStream(socket.getInputStream())); File file = new File("C:\\test.xml"); //InputStream is = new FileInputStream(file); // Get the size of the file long length = file.length(); if (length > Integer.MAX_VALUE) < System.out.println("File is too large."); >byte[] bytes = new byte[(int) length]; //out.write(bytes); System.out.println(bytes); out.close(); in.close(); socket.close(); 

Источник

Читайте также:  Vs code django html formatter

DevZone Original

Welcome again to my blog! A lot of people have asked me to share a working example of sending and receiving byte array using Java socket programming. So, below is an example for you to get started:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
// A Java program for a Server import java.net.*; import java.util.Arrays; import java.io.*; public class Server   //initialize socket and input stream private Socket socket = null; private ServerSocket server = null; private InputStream in = null; private OutputStream out = null; // constructor with port public Server(int port)   // starts server and waits for a connection try   server = new ServerSocket(port); System.out.println("Server started"); System.out.println("Waiting for a client . "); socket = server.accept(); System.out.println("Client accepted"); // takes input from the client socket in = new DataInputStream(socket.getInputStream()); //writes on client socket out = new DataOutputStream(socket.getOutputStream()); // Receiving data from client ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte buffer[] = new byte[1024]; baos.write(buffer, 0 , in.read(buffer)); byte result[] = baos.toByteArray(); String res = Arrays.toString(result); System.out.println("Recieved from client : "+res); //echoing back to client out.write(result); System.out.println("Closing connection"); // close connection socket.close(); in.close(); > catch(IOException i)   System.out.println(i); > > public static void main(String args[])   new Server(5000); > >
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
// A Java program for a Client import java.net.*; import java.util.Arrays; import java.io.*; public class Client  // initialize socket and input output streams private Socket socket = null; private OutputStream out = null; private InputStream in = null; // constructor to put ip address and port public Client(String address, int port)  // establish a connection try  socket = new Socket(address, port); if (socket.isConnected())  System.out.println("Connected"); > // sends output to the socket out = new DataOutputStream(socket.getOutputStream()); //takes input from socket in = new DataInputStream(socket.getInputStream()); > catch (UnknownHostException u)  System.out.println(u); > catch (IOException i)  System.out.println(i); > try  byte[] arr =  (byte)0x00, (byte)0x1F, (byte)0x60, (byte)0x1D, (byte)0xA1, (byte)0x09, (byte)0x06, (byte)0x07, (byte)0x60, (byte) 0x85, (byte)0x74, (byte)0x05, (byte) 0x08, (byte)0x01, (byte)0x01, (byte)0xBE, (byte)0x10, (byte)0x04, (byte)0x0E, (byte)0x01, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x06, (byte)0x5F, (byte)0x1F, (byte)0x04, (byte)0x00, (byte)0x00, (byte)0x18, (byte)0x1D, (byte)0xFF, (byte)0xFF>; // sending data to server out.write(arr); String req = Arrays.toString(arr); //printing request to console System.out.println("Sent to server : " + req); // Receiving reply from server ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte buffer[] = new byte[1024]; baos.write(buffer, 0 , in.read(buffer)); byte result[] = baos.toByteArray(); String res = Arrays.toString(result); // printing reply to console System.out.println("Recieved from server : " + res); > catch (IOException i)  System.out.println(i); > // > // close the connection try  // input.close(); in.close(); out.close(); socket.close(); > catch (IOException i)  System.out.println(i); > > public static void main(String args[])  new Client("127.0.0.1", 5000); > >

The Client sends a byte array to the Server . Server receives the byte array from the Client and sends the same byte array to the Client .
I have added comments in the code to explain the workflow more clearly.

Источник

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

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

(I’m new to Java programming, and can’t seem to find an example of how to do this that shows both ends of the connection (sender and receiver.) If you know of an existing example, maybe you could post the link. (No need to reinvent the wheel.) P.S. This is NOT homework! 🙂

9 Answers 9

The InputStream and OutputStream classes in Java natively handle byte arrays. The one thing you may want to add is the length at the beginning of the message so that the receiver knows how many bytes to expect. I typically like to offer a method that allows controlling which bytes in the byte array to send, much like the standard API.

private Socket socket; public void sendBytes(byte[] myByteArray) throws IOException < sendBytes(myByteArray, 0, myByteArray.length); >public void sendBytes(byte[] myByteArray, int start, int len) throws IOException < if (len < 0) throw new IllegalArgumentException("Negative length not allowed"); if (start < 0 || start >= myByteArray.length) throw new IndexOutOfBoundsException("Out of bounds: " + start); // Other checks if needed. // May be better to save the streams in the support class; // just like the socket variable. OutputStream out = socket.getOutputStream(); DataOutputStream dos = new DataOutputStream(out); dos.writeInt(len); if (len > 0) < dos.write(myByteArray, start, len); >> 

EDIT: To add the receiving side:

public byte[] readBytes() throws IOException < // Again, probably better to store these objects references in the support class InputStream in = socket.getInputStream(); DataInputStream dis = new DataInputStream(in); int len = dis.readInt(); byte[] data = new byte[len]; if (len >0) < dis.readFully(data); >return data; > 

@ChristopherFrancisco Loop? Just call the methods from a loop. If you mean wait for a message without stopping your program, you can just do the I/O on a separate thread or modify this to use NIO.

Have not tested it, but If len > [TCP packet size], I think readFully() might not read all the contents but just the first available parts. (docs.oracle.com/javase/7/docs/api/java/io/…) So this code might not work as is in this case, right?

@ntg i think readFully takes care of that. it reads as many packets as needed until len bytes are read. if EOF happens before that, it throws an exception

«The InputStream and OutputStream classes in Java natively handle byte arrays.» —What specifically does Java do here? Does it convert the array to a string at some point before interacting with the stream? Do you know the format it uses?

Just start with this example from the Really Big Index. Notice though, that it’s designed to transmit and receive characters, not bytes. This isn’t a big deal, though — you can just deal with the raw InputStream and OutputStream objects that the Socket class provides. See the API for more info about the different types of readers, writers and streams. Methods you’ll be interested in are OutputStream.write(byte[]) and InputStream.read(byte[]) .

The Oracle Socket Communications Tutorial would seem to be the appropriate launch point.

Note that it’s going to extra trouble to turn characters into bytes. If you want to work at the byte level, just peel that off.

This Sun Sockets tutorial should give you a good starting point

What you need to use is the write method of an java.io.OutputStream , and the read method of an java.io.InputStream , both of which you can retrieve from the Socket you open.

I would ask you to use ObjectOutputStream and ObjectInputStream. These send everything as an object and receive as the same.

ObjectOutputStream os = new ObjectOutputStream(socket.getOutputStream()); os.flush(); ObjectInputStream is = new ObjectInputStream(socket.getInputStream()); os.writeObject(byte_array_that_you_want_to_send); byte[] temp = (byte[]) is.readObject(); 

Also remember first create the output stream, flush it and then go ahead with the input stream because if something left out in the stream the input stream wont be created.

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.,

^ 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!

Источник

Оцените статью