Socket实现上传下载

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
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
//服务端server
public class upload{
public static void main(String[] args) throws Exception {
System.out.println("================服务端server==============");
ServerSocket ss = new ServerSocket(8888);
Socket socket = ss.accept();
//读取客户端发送的数据
BufferedInputStream buf = new BufferedInputStream(socket.getInputStream());
//将客户端发送的数据读取到本地
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("E:\\q1.txt"));
byte[] b = new byte[1024];
int len = 0;
//边读边写
while ((len = buf.read(b)) != -1) {
bos.write(b,0,len);
bos.flush();
}
System.out.println("写出完毕");
//发送消息到客户端
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
dos.writeUTF("上传成功");
dos.flush();
dos.close();
bos.close();
buf.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
26
27
28
29
30
31
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

//客户端
public class download {
public static void main(String[] args) throws Exception, IOException {
System.out.println("================客户端Client==============");
Socket socket = new Socket("127.0.0.1", 8888);
//获取读取文件的输入流
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("E:\\q.txt"));
//输出信息到服务端的输出流
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
byte [] b = new byte[1024];
int len = 0;
//边读边写
while((len=bis.read(b))!=-1){
bos.write(b, 0, len);
bos.flush();
}
//在不关闭socket的条件下关闭输出流
socket.shutdownOutput();
//获取服务端反馈消息的输入流
DataInputStream dis = new DataInputStream(socket.getInputStream());
String mess = dis.readUTF();
System.out.println(mess);

}
}

socket连接实现文件复制