客户端 java.net.Socket
服务端 java.net.ServerSocket

客户端和服务端直接是逻辑连接,其中包含一个IO对象(字节流对象), 服务端用客户端的流跟客户端交互。

serversocket.accept()获取客户端的Socket请求对象

Server端

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package file.upload;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class FileUploadServer {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(8000);
//获取客户端socket对象
while(true){
//获取客户端Socket对象
Socket accept = server.accept();
//网络字节输入流获取客户端数据
new Thread(new Runnable() {
//一个客户端连接,建立一个线程
@Override
public void run() {
try{
InputStream inputStream = accept.getInputStream();
//判断upload文件夹是否存在
File file = new File("D:\\upload");
if(!file.exists()){
file.mkdirs();
}
FileOutputStream fileOutputStream = new FileOutputStream(file +"\\"+System.currentTimeMillis()+".gif");

int len = 0;
byte[] bytes = new byte[1024 * 10];
while ((len = inputStream.read(bytes)) != -1) {
//写入本地
fileOutputStream.write(bytes, 0, len);
}

accept.getOutputStream().write("接收完毕".getBytes());
fileOutputStream.close();

}catch (IOException e){
e.printStackTrace();
}finally {
try {
accept.close();
}catch (IOException e){
e.printStackTrace();
}
}

}
});

}
// server.close();
}
}

Client

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
30
31
package file.upload;

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

public class FileUploadClient {
public static void main(String[] args) throws IOException {
FileInputStream file = new FileInputStream("D:\\vim.gif");
byte[] bytes = new byte[1024 * 10];
int readLen = 0;

Socket socket = new Socket("127.0.0.1", 8000);

OutputStream outputStream = socket.getOutputStream();
while ((readLen = file.read(bytes)) != -1) {//=-1读取不到结束标记
//网络字节输出流 上传到服务器
outputStream.write(bytes,0,readLen);
}
//禁用此套接字的输出流。对于TCP任何以前写入的数据都会被发送并且后面跟TCP的正常终止序列
socket.shutdownOutput();

//获取服务器输入流 接收服务器反馈
InputStream inputStream = socket.getInputStream();
while ((readLen = inputStream.read(bytes)) != -1) {
System.out.println(new String(bytes, 0, readLen));
}

file.close();
socket.close();
}
}