0

I am trying to send byte data from client to server using sockets in Java. My idea is to upload image file from client to server. But, it was not working and hence I tried to send ASCII characters to see if they are received by server. I found out that the bytes sent from client are sometimes received fully and sometimes only part of the bytes sent is received by server. Some of the bytes sent by client are lost i.e. not received on the server. Why is that happening?

Server:

void start() {
        try {
            serverSocket = new ServerSocket(1024);
            System.out.println("Server started...");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    void listen() {
        try {
            while (true) {
                Socket socket = serverSocket.accept();
                BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "utf-8"));
                String line = reader.readLine();
                String com[] = line.split(":");
                if (com[0].equalsIgnoreCase("image")) {
                    String fn = com[1];
                    long len = Long.parseLong(com[2]);
                    InputStream fin = socket.getInputStream();
                    FileOutputStream fout = new FileOutputStream("received_" + fn);
                    long i = 0;
                    int b;
                    while (i < len) {
                        b = fin.read();
                        fout.write(b);
                        System.out.print((char)b + " " );
                        i++;
                    }
                    fout.close();
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

Client:

Socket socket;
    void send() {
        try {
            socket = new Socket("localhost", 1024);
            OutputStream fout = socket.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fout, "utf-8"));
            writer.write("image:koala.jpg:11\r\n");
            writer.flush();
            int ch = 0;
            byte val[] = "hello there".getBytes("utf-8");
            while(ch < val.length){
                fout.write(val[ch]);
                ch++;
            }
            fout.flush();
            socket.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
birraa
  • 430
  • 1
  • 4
  • 15
  • This is a different question. The question here is that the server is not receiving the bytes sent by client and why? The two are completely different questions. – birraa Jun 26 '17 at 13:00
  • The issue is the `BufferedReader`, but the code in my answer in the duplicate will solve the problem. – user207421 Jun 26 '17 at 15:19
  • How is the `BufferedReader` affecting the communication or causing this? I want to know why this error is happening. – birraa Jun 27 '17 at 10:55

0 Answers0