2020-11-03

Socket编程—传输文件

/*服务器端*/
package TCP;

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

//服务端线程管理类,用于处理客户端图片上传
class ServerThread implements Runnable{
	private Socket socket;
	public ServerThread(Socket socket) {
		this.socket=socket;
	}
	public void run() {
		//1.处理客户端请求,进行上传文件保存
		String ip=socket.getInetAddress().getHostAddress();
		int count=1;
		try {
			//创建图片上传保存目录
			File parentFile = new File("D:\\upload\\");
			if(!parentFile.exists()) {
				parentFile.mkdir();
			}
			//把客户端的IP地址作为上传文件的文件名
			File file = new File(parentFile,ip+"("+count+").jpg");
			while(file.exists()) {
				file= new File(parentFile,ip+"("+(count++)+").jpg");
			}
			//通过客户端输入流读取上传图片写入到指定目录
			InputStream in = socket.getInputStream();
			FileOutputStream fos = new FileOutputStream(file);
			byte[] buf= new byte[1024];
			int len=0;
			while((len=in.read(buf))!=-1) {
				fos.write(buf,0,len);
			}
			//2.服务器端向客户端做出响应,返回消息
			OutputStream out = socket.getOutputStream();
			out.write("上传成功".getBytes());
			//关闭流和Socket连接
			in.close();
			fos.close();
			socket.close();
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
}
public class UploadTCPServer {

	public static void main(String[] args) throws Exception{
		// 创建指定端口号为8080的服务端ServerSocket对象
		ServerSocket serverSocket = new ServerSocket(8080);
		while(true) {
			//调用accept()方法持续接收客户端请求
			Socket client=serverSocket.accept();
			//针对每一个客户端请求创建一个线程进行连接管理
			new Thread(new ServerThread(client)).start();
		}

	}

}
/*客户端*/
package TCP;

import java.io.*;
import java.net.*;
import java.net.InetAddress;

//客户端程序
public class UploadTCPClient {

	public static void main(String[] args) throws Exception {
		// 创建一个socket并连接到指定的服务器端(上面运行程序的计算机ip)
		Socket client = new Socket("110.65.101.22", 8080);
		// 客户端向服务器端上传文件
		OutputStream out = client.getOutputStream();
		FileInputStream fis = new FileInputStream("D:\\222.jpg");
		byte[] buf = new byte[1024];
		int len = 0;
		System.out.println("连接服务器,开始上传");
		while ((len = fis.read(buf)) != -1) {
			out.write(buf, 0, len);
		} // 图片上传完成后,要及时关闭客户端输出流
		client.shutdownOutput();
		// 客户端接收服务器的响应信息
		InputStream is = client.getInputStream();
		byte[] bufMsg = new byte[1024];
		int len2 = is.read(bufMsg);
		while (len2 != -1) {
			System.out.println(new String(bufMsg, 0, len2));
			len2 = is.read(bufMsg);
		}
		out.close();
		is.close();
		fis.close();
		client.close();

	}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值