java network programming -TCP- upload files

Socket stream input and output between the server and the client transport only, it is necessary to read the file byte stream additional content is then Socket stream writing, when stored, the server reads the Socket stream stream when extra bytes to write to file

Client: Upload file

public class tcp2 {

public static void main(String[]args) throws IOException
{
    System.out.println("客户端启动中");

    Socket client =new Socket("localhost",8888);

    //文件的拷贝
    InputStream is=new BufferedInputStream(new FileInputStream("src\\linux学习路线.png"));
    OutputStream os=new BufferedOutputStream(client.getOutputStream());

    byte[] data=new byte[1024*60];
    int len=-1;
    while((len=is.read(data))!=-1)
    {
        os.write(data,0,len);
    }
    os.flush();
    os.close();

    client.close();

}
}

Server: storage file

public class tcp {

public static void main(String[]args) throws IOException
{
    System.out.println("服务器启动中...");
    ServerSocket server=new ServerSocket(8888);

    Socket client=server.accept();

    //文件的拷贝
    InputStream is=new BufferedInputStream(client.getInputStream());
    OutputStream os=new BufferedOutputStream(new FileOutputStream("D:/d/tu.jpg"));

    byte[] flush=new byte[1024*60];
    int len=-1;

    while((len=is.read(flush))!=-1)
    {
        os.write(flush,0,len);
    }

    is.close();
    os.close();

    client.close();

}
}

Guess you like

Origin blog.51cto.com/14437184/2433084