1.client
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
public class TcpClientDemo {
public static void main(String[] args) {
InetAddress byName = null;
Socket socket = null;
OutputStream os = null;
FileInputStream fis = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
// 1. 获取服务器地址和端口
byName = InetAddress.getByName("127.0.0.1");
int port = 9999;
// 2. 创建socket
socket = new Socket(byName, port);
// 3. 读取文件
os = socket.getOutputStream();
fis = new FileInputStream(new File("example.jpg"));
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
// 4. 通知服务器传输结束
socket.shutdownOutput();
// 5. 接受服务器传输完毕会话后,才断开连接
is = socket.getInputStream();
baos = new ByteArrayOutputStream();
int len2;
byte[] buffer2 = new byte[1024];
while ((len2 = is.read(buffer2)) != -1) {
baos.write(buffer2, 0, len2);
}
System.out.println(baos);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
os.close();
fis.close();
is.close();
baos.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2.server
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
public class TcpServerDemo {
public static void main(String[] args) {
ServerSocket serverSocket = null;
InputStream is = null;
Socket socket = null;
OutputStream os = null;
FileOutputStream baos = null;
try {
// 1. 创建server端
serverSocket = new ServerSocket(9999);
// 2.阻塞式监听
socket = serverSocket.accept();
// 3.读取客户端的消息
is = socket.getInputStream();
// 4.管道流
baos = new FileOutputStream(new File("receive.jpg"));
// 读入的缓冲区
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
// 通知客户端传输结束
os = socket.getOutputStream();
os.write("transmission complete.".getBytes(StandardCharsets.UTF_8));
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
baos.close();
is.close();
os.close();
socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
执行结果: