TCP文件上传

TCP文件上传

实现文件上传与服务器文件下载与拷贝。

文件服务器:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* 文件服务器(下载|拷贝):
* 1.指定端口,使用ServerSocket创建服务器
* 2.阻塞式等待链接 accept 返回一个Socket
* 3.操作:输入输出流
* 4.释放资源
*/
public class File_Server {
public static void main(String[] args) throws Exception {
System.out.println("-------Server-------");
//1.指定端口,使用ServerSocket创建服务器
ServerSocket SS=new ServerSocket(6666);
// 2.阻塞式等待链接 accept
Socket Client=SS.accept();
System.out.println("客户端连接已建立");
// 3.操作:输入输出流
InputStream buf=new BufferedInputStream(Client.getInputStream());
OutputStream bof=new BufferedOutputStream(new FileOutputStream("c.txt"));
byte b[]=new byte[1024];
while(buf.read(b)!=-1) {
bof.write(b);
}
bof.flush();
// 4.释放资源
bof.close();
buf.close();
Client.close();
}
}

文件客户端:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* 文件客户端(上传):
* 1.建立连接:使用Socket创建客户端:服务器地址和端口
* 2.操作:输入输出流
* 3.释放资源
*/
public class File_Client {
public static void main(String[] args) throws Exception {
System.out.println("-------Client-------");
//1.建立连接:使用Socket创建客户端:服务器地址和端口
Socket S=new Socket("localhost",6666);
// 3.操作:输入输出流
InputStream buf=new BufferedInputStream(new FileInputStream("D:/javawork/java 17级软工学生体测数据统计系统/用户信息.txt"));
OutputStream bof=new BufferedOutputStream(S.getOutputStream());
byte b[]=new byte[1024];
while(buf.read(b)!=-1) {
bof.write(b);
}
bof.flush();
// 4.释放资源
S.close();
buf.close();
bof.close();
}
}
原创技术分享,您的支持将鼓励我继续创作
0%