//服务器端
public class TCPServer {
public static void main(String[] args) throws IOException {
//1.创建服务器对象ServerSocket,明确端口号
ServerSocket server=new ServerSocket(8888);
//2.调用accept方法,跟客户端创建连接,并获取连接的客户端对象
Socket socket=server.accept();
//3.明确目的地
File file=new File("D:\\nihao");
//如果该目录不存在则创建
if(!file.exists()){
file.mkdirs();
}
String filename="Oracle"+System.currentTimeMillis()+".txt";
//明确目的地
FileOutputStream fos=new FileOutputStream(file+File.separator+filename);
//明确数据源
InputStream in=socket.getInputStream();
//开始复制
int len=0;
byte[] bytes=new byte[1024];
while((len=in.read(bytes))!=-1){
fos.write(bytes,0,len);
}
//回复客户端
//获取字节输出流 ,回复客户端
OutputStream out =socket.getOutputStream();
out.write("上传成功".getBytes());
//释放资源
fos.close();
server.close();
}
}
//客户端
public class TCPClient {
public static void main(String[] args) throws UnknownHostException, IOException {
//1.创建Socket对象,明确要连接的服务器地址和端口号
Socket socket =new Socket("127.0.0.1",8888);
//2.明确数据源
FileInputStream fis=new FileInputStream("D:\\java\\a.txt");
//3.从socke对象中获取字节输出流,准备把读的文件字节写给服务器
OutputStream out=socket.getOutputStream();
//4.开始复制
int len=0;
byte[] bytes=new byte[1024];
while((len=fis.read(bytes))!=-1){
out.write(bytes,0,len);
}
//结束输出流,告诉服务器结束了,不要读了
socket.shutdownOutput();
//接收服务器的回复
//1.从socket对象中获取字节输入流,接收服务器回复的数据
InputStream in=socket.getInputStream();
len=in.read(bytes);
System.out.println(new String(bytes,0,len));
//释放资源
socket.close();
fis.close();
}
}
2、多线程传输:
//线程任务对象
public class Upload implements Runnable {
private Socket socket;
public Upload() {
};
public Upload(Socket socket) {
this.socket = socket;
};