目录
需求: 客户端上传图片至服务端,服务端接收图片并保存至本地
客户端 Client_img
package Internet.SocketImg;
import Internet.Utility.StreamUtils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.Socket;
public class Client_img {
public static void main(String[] args) throws Exception {
//连接服务端端口
Socket socket = new Socket(InetAddress.getLocalHost(), 8888);
//读取图片
String filePath="C:\\Users\\123\\Pictures\\Camera Roll\\OIP-C.jpg";
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath));
//图片转字节数组
byte[] bytes = StreamUtils.streamToByteArray(bis);
//发送至服务端
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
bos.write(bytes);
bos.flush();
bis.close();
socket.shutdownOutput();//结束标记
//接收服务器返回信息
InputStream inputStream = socket.getInputStream();
String s = StreamUtils.streamToString(inputStream);
System.out.println(s);
//关闭流
bos.close();
inputStream.close();
socket.close();
}
}
服务端 Server_img
package Internet.SocketImg;
import Internet.Utility.StreamUtils;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Server_img {
public static void main(String[] args) throws Exception {
//监听端口
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("服务端在8888端口等待连接~");
//等待连接
Socket socket = serverSocket.accept();
//读取客户端的数组
BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
byte[] bytes = StreamUtils.streamToByteArray(bis);
//将数组写入磁盘
String destPath="src\\img.png";
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destPath));
bos.write(bytes);
bos.flush();
bos.close();
//返回接收通知
BufferedWriter br = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
br.write("Server successfully accepted~");
br.flush();
socket.shutdownOutput();
//关闭流
br.close();
bis.close();
socket.close();
serverSocket.close();
}
}
工具类:将文件转化为字节数组
package Internet.Utility;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
//将文件转化为byte[]
public class StreamUtils {
public static byte[] streamToByteArray(InputStream is) throws Exception {
// 创建输出流对象
ByteArrayOutputStream bos = new ByteArrayOutputStream();
// 字节数组
byte[] b = new byte[1024];
int len;
while ((len = is.read(b)) != -1) {
// 循环读取
// 把读取到的数据,写入 bos
bos.write(b, 0, len);
}
byte[] array = bos.toByteArray();
bos.close();
return array;
}
public static String streamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line + "\r\n");
}
return builder.toString();
}
}
学习总结
Buffered缓冲流每次用完都要记得flush刷新一次