// 1. 创建一个服务端套接字
ServerSocket serverSocket = new ServerSocket(8088);
log.info("服务端开启");
while (true) {
log.info("循环进行查找jpeg的头");
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
BufferedOutputStream bos = null;
FileOutputStream fos = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
String milliDate = sdf.format(new Date());
int receiveBufferSize = socket.getReceiveBufferSize();
byte[] buf = new byte[receiveBufferSize];
int lens = -1;
boolean flag = false;
while ((lens = inputStream.read(buf)) != -1)
{
String strHex = "";
for (int n = 0; n < buf.length; n++) {
strHex = Integer.toHexString(buf[n] & 0xFF);
// 每个字节由两个字符表示,位数不够,高位补0
if (strHex.equals("ff") && n != buf.length - 1) {
String startHex2 = Integer.toHexString(buf[n + 1] & 0xFF);
if (startHex2.equals("d8")) {
flag = true;
log.info("找到图片的头了");
String path = "D:" + File.separator + "ANPRPicture";
File file = new File(path);
if (!file.isDirectory()) {
//创建文件上传目录
file.mkdirs();
}
String realPath = path + "\\" + milliDate + ".jpg";
log.info("图片存在服务器中的地址为:" + path);
fos = new FileOutputStream(realPath);
bos = new BufferedOutputStream(fos);
}
if (startHex2.equals("d9")) {
bos.write(buf[n]);
bos.write(buf[n + 1]);
flag = false;
log.info("找到图片的尾了");
if (null != bos) {
bos.flush();
bos.close();
}
if (null != fos) {
fos.close();
}
log.info("关闭文件输出流");
}
}
if (flag) {
bos.write(buf[n]);
}
};