TCP:利用Socket编程技术实现客户端向服务端上传一个图片。

问题:

利用Socket编程技术实现客户端向服务端上传一个图片的程序。

客户端:

import java.io.*;
import java.net.Socket;

public class client
{
    public static byte[] getimg(String imgpath) throws IOException
    {
        FileInputStream img = new FileInputStream(imgpath); //读取图片的字节流
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] res = new byte[1024];
        int num = 0;
        while ((num = img.read(res)) != -1)
        {
            out.write(res, 0, num); //写入
        }
        return out.toByteArray();
    }
    public static void main(String[] args) throws IOException
    {
        Socket s = new Socket("127.0.0.1", 10000);
        OutputStream out = s.getOutputStream();
        byte[] a = getimg("E:\\1.jpg"); //得到图片的字节数组
        out.write(a); //写入
        s.close();
        out.close();
    }
}

服务端:

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class server
{
    public static void main(String[] args) throws IOException
    {
        ServerSocket now = new ServerSocket(10000);
        Socket s = now.accept();
        InputStream in = s.getInputStream();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int tr;
        byte[] u = new byte[1024];
        while ((tr = in.read(u)) != -1)
        {
            out.write(u, 0, tr); //写入out
        }
        FileOutputStream fileout = new FileOutputStream("E:\\2.jpg");
        fileout.write(out.toByteArray()); //写入图片文件
        out.close();
    }
}

实验结果:

                  

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值