网络编程:TCP上传图片

【需求】:TCP上传图片

【代码一】:

/*
TCP发送图片D:\\WorkSpace\\测试.png

*/

import java.io.*;
import java.net.*;
//客户端
class  PicClient
{
	public static void main(String[] args) throws Exception
	{
		Socket s=new Socket("127.0.0.1",10006);
		//读入图片
		BufferedInputStream bis=new BufferedInputStream(new FileInputStream("D:\\WorkSpace\\测试.png"));
		//输出口
		BufferedOutputStream out=new BufferedOutputStream(s.getOutputStream());
		//输入口
		BufferedInputStream in=new BufferedInputStream(s.getInputStream());
		int len=0;
		byte[] buf=new byte[1024];
		while((len=bis.read(buf))!=-1){
			out.write(buf,0,len);
		}
		s.shutdownOutput();
		byte[] bufIn=new byte[1024];
		int num=in.read(bufIn);
		System.out.println(new String(bufIn,0,num));
		bis.close();
		s.close();

	}
}

//服务端
class  PicServer
{
	public static void main(String[] args) throws Exception
	{
		ServerSocket ss=new ServerSocket(10006);
		Socket s=ss.accept();
		String ip=s.getInetAddress().getHostAddress();
		System.out.println(ip+"已连接...");

		//输入口
		BufferedInputStream in=new BufferedInputStream(s.getInputStream());
		//输出口
		BufferedOutputStream out=new BufferedOutputStream(s.getOutputStream());
		//读入图片
		BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("D:\\WorkSpace\\网络编程\\test.png"));
		int len=0;
		byte[] buf=new byte[1024];
		while((len=in.read(buf))!=-1){
			bos.write(buf,0,len);
		}
		out.write("上传成功".getBytes());
        out.flush();
        //之前没有写flush(),客户端的int num=in.read(bufIn);输出为-1,就会报异常
		bos.close();
		s.close();
		ss.close();
	}
}

【截图一】:

 

【代码二】:


import java.io.*;
import java.net.*;
class  PicClient2
{
	public static void main(String[] args) throws Exception
	{
		Socket s=new Socket("127.0.0.1",10007);
		FileInputStream fis=new FileInputStream("D:\\WorkSpace\\测试.png");
		OutputStream out=s.getOutputStream();
		InputStream in=s.getInputStream();
		int len=0;
		byte[] buf=new byte[1024];
		while((len=fis.read(buf))!=-1){
			out.write(buf,0,len);
		}
		s.shutdownOutput();
		byte[] bufIn=new byte[1024];
		int num=in.read(bufIn);
		System.out.println(new String(bufIn,0,num));
		fis.close();
		s.close();
	}
}

class  PicServer2
{
	public static void main(String[] args) throws Exception
	{
		ServerSocket ss=new ServerSocket(10007);
		Socket s=ss.accept();
		String ip=s.getInetAddress().getHostAddress();
		System.out.println(ip+"is connected...");

		InputStream in=s.getInputStream();
		OutputStream out=s.getOutputStream();
		FileOutputStream fos=new FileOutputStream("D:\\WorkSpace\\网络编程\\测试.png");

		int len=0;
		byte[] buf=new byte[1024];
		while((len=in.read(buf))!=-1){
			fos.write(buf,0,len);
		}
		out.write("上传成功".getBytes());
		fos.close();
		s.close();
		ss.close();
	}
}

【截图二】:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值