TCP文件上传
TCP文件上传
服务器端:
- 确定接收地址--端口
- 监听连接 accept
- 获取输入流
- 将输入流写入文件输出流
- 通知客户端已完成接收
- 关闭资源
客户端:
- 建立连接 socket
- 读取文件流
- 将文件流写入socket输出流
- 结束输出流 shutdownOutput
- 等待客户端完成接收
- 关闭资源
服务器端:
package com.example.network;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServerDemo02 {
public static void main(String[] args) throws IOException {
// 传输文件 从客户端发出,服务器端接收
// 建立链接地址
ServerSocket serverSocket = new ServerSocket(9000);
// 监听连接
Socket socket = serverSocket.accept();
// 获取输入流
InputStream is = socket.getInputStream();
// 输入流写入文件
FileOutputStream fos = new FileOutputStream("receive.jpg");
byte[] buffer = new byte[1024];
int len;
while ((len = (is.read(buffer))) != -1) {
fos.write(buffer, 0, len);
}
// 通知客户端已获取完毕
OutputStream outputStream = socket.getOutputStream();
outputStream.write("接收完毕".getBytes());
// 关闭资源
fos.close();
is.close();
socket.close();
serverSocket.close();
}
}
客户端:
package com.example.network;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
public class TcpClientDemo02 {
public static void main(String[] args) throws IOException {
// 传输文件 从客户端发出,服务器端接收
// 获取ip
InetAddress serverIp = InetAddress.getByName("127.0.0.1");
// 创建连接
Socket socket = new Socket(serverIp, 9000);
OutputStream os = socket.getOutputStream();
// 文件流写入输出流
FileInputStream fis = new FileInputStream("200829121036-11425.jpg");
byte[] buffer = new byte[1024];
int len;
while ((len = (fis.read(buffer))) != -1) {
os.write(buffer, 0, len);
}
// 告诉服务端已发送完成
socket.shutdownOutput();
// 如果客户端获取完毕,才能关闭资源
InputStream is = socket.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer2 = new byte[1024];
int len1;
while ((len1 = is.read(buffer2)) != -1) {
baos.write(buffer2, 0, len1);
System.out.println(baos);
}
// 关闭资源
fis.close();
os.close();
socket.close();
}
}