gogasca
gogasca

Reputation: 10058

Java custom Protocol client-server

I'm trying to create a client-server application in Java. This application will be transferring images from client to server. The requirements is that application needs to be in network byte order. (Image below)

This will help me to learn how to deploy other protocols in the future, so looking for some tips in how to implement this. Currently I have my server-client working and transferring images, but not sure how to implement the protocol.

Thanks

This is my current server/client code:

public class NetworkServer {

public static void main(String[] args) { NetworkServer servidor = new NetworkServer(); System.out.println("Server started()"); BufferedInputStream bis; BufferedOutputStream bos; int num; File file = new File("/images"); if (!(file.exists())){ file.mkdir(); } try { ServerSocket socket = new ServerSocket(15000); Socket incoming = socket.accept(); try { try{ if (!(file.exists())){ file.mkdir(); } InputStream inStream = incoming.getInputStream(); OutputStream outStream = incoming.getOutputStream(); BufferedReader inm = new BufferedReader(new InputStreamReader(inStream)); PrintWriter out = new PrintWriter(outStream, true /* autoFlush */); String filelength = inm.readLine(); String filename = inm.readLine(); System.out.println("Server() Filename = " + filename); System.out.println("Server() File lenght: " + filelength + " bytes"); System.out.println("Server() ACK: Filename received = " + filename); //RECIEVE and WRITE FILE byte[] receivedData = new byte[1000000]; bis = new BufferedInputStream (incoming.getInputStream()); bos = new BufferedOutputStream (new FileOutputStream("/images" + "/" + "image.jpg")); while ( (num = bis.read(receivedData)) > 0){ bos.write(receivedData,0,num); } bos.close(); bis.close(); File receivedFile = new File(filename); long receivedLen = receivedFile.length(); System.out.println("Server() ACK: Length of received file = " + receivedLen); } finally { incoming.close(); } } catch (IOException e){ e.printStackTrace(); } } catch (IOException e1){ e1.printStackTrace(); } } }

Protocol

Upvotes: 1

Views: 2269

Answers (1)

Aaron Digulla
Aaron Digulla

Reputation: 328674

Another name for "Network byte order" is "big endian" (see Wikipedia).

Now you need to find a class in Java which supports big endian encoding for ints. That's not as simple as it should be because the documentation avoids standard terms like "Network byte order" or "big endian". Your lesson here: Documentation is much more useful when you can find what you need by using standard search terms.

That said, the class you're looking for is DataInputStream:

Reads four input bytes and returns an int value. Let a-d be the first through fourth bytes read. The value returned is:

    (((a & 0xff) << 24) | ((b & 0xff) << 16) |
     ((c & 0xff) << 8) | (d & 0xff))

(documentation for readInt()).

Upvotes: 3

Related Questions