JavaTCP网络通信编程实现图片传输案例

例题:

  1. 编写一个服务端,和一个客户端服务器端在8888端口监听

  2. 客户端连接到服务端,发送一张图片

  3. 服务器端接收到客户端发送的图片,保存到磁盘下.发送“收到图片”再退出

  4. 客户端接收到服务端发送的“收到图片”,再退出

服务端代码:

public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8888);
        Socket socket = serverSocket.accept();
        //将网络通道的内容读取到字节数组
        InputStream inputStream = socket.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(inputStream);
        byte[] bytes = new byte[1024];
        int date=0;
        //将字节数组读取到磁盘
        String destFile = "";//将文件存储到磁盘路径
        FileOutputStream fos = new FileOutputStream(destFile);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        while ((date=bis.read(bytes))!=-1){
            bos.write(bytes,0,date);
            bos.flush();//刷新
        }
        socket.shutdownInput();

        //回复消息
        BufferedWriter bw = new BufferedWriter(
                new OutputStreamWriter(socket.getOutputStream()));
        bw.write("收到图片");
        bw.newLine();//设置结束标记
        bw.flush();//刷新

        //关流
        bw.close();
        bos.close();
        bis.close();
        socket.close();
        serverSocket.close();

    }

 客户端代码:

 public static void main(String[] args) throws IOException {
        //InetAddress.getLocalHost()是我本机的ip地址,如果你要给别的计算机发送只需要把ip换一下即可
        Socket socket = new Socket(InetAddress.getLocalHost(), 8888);
        //把磁盘的照片读取到字节数组
        String pathFile = "";//从磁盘读取文件路径
        FileInputStream fileInputStream = new FileInputStream(pathFile);
        BufferedInputStream bis = new BufferedInputStream(fileInputStream);
        byte[] bytes = new byte[1024];
        int date = 0;
        //将字节数组写入到网络通道
        OutputStream outputStream = socket.getOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(outputStream);
        while ((date=bis.read(bytes))!=-1){
            bos.write(bytes,0,date);
            bos.flush();//刷新
        }
        socket.shutdownOutput();

        //接收消息
        BufferedReader br = new BufferedReader(
                new InputStreamReader(socket.getInputStream()));
        String s = br.readLine();
        System.out.println(s);

        //关流
        br.close();
        bos.close();
        bis.close();
        socket.close();
    }

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值