套接字从客户端发送的数据未被服务器接收

时间:2017-06-26 11:02:19

标签: java sockets network-programming

我正在尝试使用Java中的套接字将字节数据从客户端发送到服务器。我的想法是将图像文件从客户端上传到服务器。但是,它不起作用,因此我尝试发送ASCII字符以查看它们是否被服务器接收。我发现从客户端发送的字节有时会被完全接收,有时只有部分发送的字节被服务器接收。客户端发送的一些字节丢失,即未在服务器上接收。为什么会这样?

服务器:

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();
        }
    }

客户:

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();
        }
    }

0 个答案:

没有答案