Java网络编程模拟客户端和服务器的文件传输

模拟客户端和服务器的文件传输

使用两个类:
一、ServerSocket
构造方法:ServerSocket(int port)
方法:accept() 返回Socket对象
二、Socket
构造方法:Socket(String ip, int port) :连接指定ip和端口号
方法: getOutputStream() 返回 OutputStream 对象,用于给另一端传流
getInputStream() 返回InputStream 对象,得到另一端传来的流
close() 关闭创建的对象
shutdownOutput() 给传出的流加上结束符号,便于另一端读取

在这里插入图片描述

服务器端:

public class dd {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(55565);
         Socket socket=serverSocket.accept();
         InputStream is=socket.getInputStream();
         FileOutputStream fos=new FileOutputStream("C:\\Users\\asus\\Pictures\\Screenshots\\余霜.png");
         byte[] bytes=new byte[1024];
         int i=0;
         while ((i=is.read(bytes))!=-1){
             fos.write(bytes);
         }
       
        System.out.println("这里成功");
         OutputStream os=socket.getOutputStream();
         os.write("上传成功".getBytes());
        System.out.println(".............");
         os.close();
         fos.close();
         socket.close();
         serverSocket.close();
        }


}

客户端:

public class aa {
    public static void main(String[] args) throws IOException {
        Socket socket=new Socket("127.0.0.1",55565);
        FileInputStream fi=new FileInputStream("C:\\Users\\asus\\Pictures\\Screenshots\\屏幕截图(1).png");
        OutputStream os=socket.getOutputStream();

        byte[] bytes=new byte[1024];
        while (fi.read(bytes)!=-1){
            os.write(bytes);
        }
        socket.shutdownOutput();                    //暂定

        System.out.println("这里成功");
        InputStream is=socket.getInputStream();
        byte[] bytes1=new byte[1024];
        int len=is.read(bytes1);
        System.out.println(new String(bytes1,0,len));
        System.out.println("................");
        is.close();
        os.close();
        fi.close();
        socket.close();
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值