TCP文件上传实现

TCPServer:

package cn.it.inetaddress;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;

public class TCPServer {
	public static void main(String[] args) throws IOException {
		//创建服务器,等待客户端连接
		ServerSocket serverSocket = new ServerSocket(8808);
		//接收Client的Socket
		Socket accept = serverSocket.accept();
		//获取Socket的输入流
		InputStream inputStream = accept.getInputStream();
		//自定义不重复文件名
		String fileName = "it"+System.currentTimeMillis()+new Random().nextInt(999999)+".png";
		//创建字节输出流
		FileOutputStream fileOutputStream = new FileOutputStream("D:\\svn"+File.separator+fileName);
		int len = 0;
		byte[] b = new byte[1024];
		//把Socket输入流中的数据,写入目的地的字节输出流中
		while((len = inputStream.read(b)) != -1){
			fileOutputStream.write(b, 0, len);
		}
		//回复
		accept.getOutputStream().write("OK".getBytes());
		
		fileOutputStream.close();
		accept.close();
		serverSocket.close();
	}
}

TCPClient:

package cn.it.inetaddress;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class TCPClient {
	public static void main(String[] args) throws IOException{
		//创建客户端Socket,连接服务器
		Socket socket = new Socket("127.0.0.1", 8808);
		//获取Socket流中的输出流,把数据写到服务器
		OutputStream outputStream = socket.getOutputStream();
		//创建字节输入流,读取图片的字节
		FileInputStream fis = new FileInputStream("D:\\upload"+File.separator+"22622694_p0.png");
		int len = 0;
		byte[] b = new byte[1024];
		//把图片数据写到Socket的输出流中(把数据传给服务器)
		while((len = fis.read(b)) != -1){
			outputStream.write(b, 0, len);
		}
		//禁用此Socket的输出流,间接的相当于告知了服务器数据写入完毕
		socket.shutdownOutput();
		//获取Socket的输入流   读回复信息
		InputStream inputStream = socket.getInputStream();
		int read = inputStream.read(b);
		System.out.println(new String(b,0,read));
		
		fis.close();
		socket.close();
		
		
	}
}

 

你可能感兴趣的:(Java)