欢迎来到这里

socket长链接
socket

服务端
package com.xfjf.framework.test;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mytest.cvcuda;
import com.mytest.imgprecess;
import com.mytest.test;
import com.xfjf.framework.dto.ai.MatYoloForwardPoint;
import com.xfjf.framework.entity.dto.ArAigorithmModelDTO;
import com.xfjf.framework.util.ONNXModelInferenceUtil;
import com.xfjf.framework.util.StringUtils;
import com.xfjf.framework.util.http.HttpUtils;
import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;
import java.io.*;
import java.lang.reflect.Type;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SocketServer20230903 {
private final static String SOAP_BEGIN = "<SOAP-ENV:Envelope";
private final static String SOAP_END = "</SOAP-ENV:Envelope>";
public static List<cvcuda> cvcudaList = new ArrayList<>();
private static imgprecess instance;
public static synchronized imgprecess getInstance() {
if (instance == null) {
instance = new imgprecess();
}
return instance;
}
public static synchronized List<cvcuda> getCvcudaListInstance() {
if (StringUtils.isEmpty(cvcudaList) ) {
obtainModel();
}
return cvcudaList;
}
public static List<ArAigorithmModelDTO> arAigorithmModelDTOS = new ArrayList<>();
public static List<ArAigorithmModelDTO> obtainModel() {
System.out.println("初始化模型数据");
cvcudaList.clear();
Map<String, Object> params = new HashMap<String, Object>();//请求参数
try {
Gson gson = new Gson();
String url = "http://127.0.0.1:8080/system/aigorithmmodel/queryArAigorithmModelAndClass";
String json= HttpUtils.sendRequst(url, params,"GET");
Type listType = new TypeToken<List<ArAigorithmModelDTO>>() {}.getType();
arAigorithmModelDTOS = gson.fromJson(json, listType);
for(ArAigorithmModelDTO aigorithmModelDTO : arAigorithmModelDTOS){
cvcuda yolo_cuda = new cvcuda();
int use_gpu = 1;
int w = 1280;
int h = 736;
int num_class = aigorithmModelDTO.getModelClassDTOList().size();
float confidence = 0.5f;
yolo_cuda.loadModel(aigorithmModelDTO.getFilePath(),use_gpu,confidence,w,h,num_class);
cvcudaList.add(yolo_cuda);
}
return arAigorithmModelDTOS;
} catch (Exception e) {
e.printStackTrace();
}
return new ArrayList<>();
}
private ServerSocket serverSocket;
public static void main(String[] args) throws IOException {
SocketServer20230903 socketServer = new SocketServer20230903();
getCvcudaListInstance();
getInstance();
socketServer.start();
}
public SocketServer20230903() throws IOException {
serverSocket = new ServerSocket(18889);
}
public void start() throws IOException {
while (true) {
try {
Socket socket = serverSocket.accept();
new SocketThread(socket).start();
} catch (IOException e) {
}
}
}
class SocketThread extends Thread {
private final Socket socket;
private final OutputStream out;
private final InputStream inputStream;
private final AtomicInteger frameCount;
private AtomicInteger countBytesRead ;
private final ByteArrayOutputStream byteArrayOutputStream;

public SocketThread(Socket socket) throws IOException {
this.socket = socket;
this.frameCount = new AtomicInteger(0);
this.out = socket.getOutputStream();
this.inputStream = socket.getInputStream();
this.countBytesRead = new AtomicInteger(0);
this.byteArrayOutputStream = new ByteArrayOutputStream();
}
public void run() {
try {
Integer bufferSize = 0 ;
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
String receivedData = new String(buffer, 0, bytesRead, StandardCharsets.UTF_8);
// System.out.println(receivedData);
if (receivedData.indexOf(SOAP_BEGIN) != -1 && receivedData.indexOf(SOAP_END) != -1) {
Pattern pattern = Pattern.compile("<SOAP-ENV:Envelope>(\\d+)</SOAP-ENV:Envelope>");
Matcher matcher = pattern.matcher(receivedData);
while (matcher.find()) {
bufferSize = Integer.parseInt(matcher.group(1));
countBytesRead.set(0);
}
continue;
}
synchronized (this) {
byteArrayOutputStream.write( buffer, 0, bytesRead);
countBytesRead.addAndGet(bytesRead);
if(countBytesRead.get() == bufferSize){
Mat mat = ONNXModelInferenceUtil.identification_(byteArrayOutputStream.toByteArray());
if (mat != null && !mat.empty()) {
String filename = "d://a/received_image"+ frameCount +".jpg";
Imgcodecs.imwrite(filename, mat);
try{
MatYoloForwardPoint matYoloForwardPoint = test.recognitionUserGpu(mat,cvcudaList
,arAigorithmModelDTOS,instance);
Gson gson = new Gson();
String json = gson.toJson(matYoloForwardPoint);
synchronized (out) {
out.write(json.getBytes());
// out.write("2".getBytes());
}
}catch (Exception e){
e.getStackTrace();
}
}
byteArrayOutputStream.reset();
frameCount.incrementAndGet();
countBytesRead.set(0);
}
}

}
} catch (Exception e) {
e.getStackTrace();
System.out.println(e.getMessage());
} finally {
synchronized (socket) {
if (socket != null && !socket.isClosed()) {
try {
MatYoloForwardPoint matYoloForwardPoint = new MatYoloForwardPoint();
Gson gson = new Gson();
String json = gson.toJson(matYoloForwardPoint);
synchronized (out) {
out.write(json.getBytes());
}
socket.close();
} catch (IOException e) {
e.getStackTrace();
}
}
}
}
}
}
private String queryThreadId() {
return Long.toString(Thread.currentThread().getId());
}
}
 
客户端
package com.xfjf.framework.test;

import java.io.*;
import java.net.Socket;
public class SocketClient120230903 {
class SendThread extends Thread{
private Socket socket;
public SendThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
while(true){
try {
for(int i=1;i<=4;i++){
File imageFile = new File("d://"+i+".jpg");
String send = getSend(imageFile.length());
PrintWriter pw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
pw.write(send);
pw.flush();
FileInputStream fileInputStream = new FileInputStream(imageFile);
byte[] imageBytes = new byte[(int) imageFile.length()];
fileInputStream.read(imageBytes);
fileInputStream.close();
OutputStream out = socket.getOutputStream();
out.write(imageBytes);
out.flush();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public String getSend(long as) throws InterruptedException{
Thread.sleep(1000);
return "<SOAP-ENV:Envelope>"+as+"</SOAP-ENV:Envelope>";
}
}
class ReceiveThread extends Thread{
private Socket socket;
public ReceiveThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
while(true){
InputStream inputStream = null;
try {
inputStream = socket.getInputStream();
byte[] buffer = new byte[1024];
int bytesRead = inputStream.read(buffer);
if (bytesRead != -1) {
String responseString = new String(buffer, 0, bytesRead);
System.out.println(responseString);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public void start() throws IOException{
Socket socket = new Socket("127.0.0.1",18889);
System.out.println("clent run");
new SendThread(socket).start();
new ReceiveThread(socket).start();
}
public static void main(String[] args) throws IOException {
// new SocketClient120230903().start();
SocketClient120230903 client1 = new SocketClient120230903();

SocketClient120230903 client2 = new SocketClient120230903();

SocketClient120230903 client3 = new SocketClient120230903();

SocketClient120230903 client4 = new SocketClient120230903();

SocketClient120230903 client5 = new SocketClient120230903();

SocketClient120230903 client6 = new SocketClient120230903();

client1.start();
client2.start();
client3.start();
client4.start();
client5.start();
client6.start();
}
}
赞这个主题
1,048
用户 liu 发布于
Sep 4, 2023 10:21:44 AM
用户 liu 最后回复于
Sep 4, 2023 10:21:44 AM

评论区

liu
package com.inspection_rn; import java.util.concurrent.ConcurrentLinkedQueue; public class LinkedQueueStringUtil { private ConcurrentLinkedQueue queue = new ConcurrentLinkedQueue<>(); public void clear()// 销毁队列 { queue.clear(); } public boolean isQueueEmpty()// 判断队列是否为空 { return queue.isEmpty(); } public void enQueue(MatYoloForwardPoint o)// 进队 { queue.offer(o); } public MatYoloForwardPoint deQueue()// 出队 { return queue.poll(); } public int QueueLength()// 获取队列长度 { return queue.size(); } public MatYoloForwardPoint QueuePeek()// 查看队首元素 { return queue.peek(); } } }
liu
List dict_list = null ; MatYoloForwardPoint forwardResultItem1 =null; public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) { Mat frame = inputFrame.rgba(); try{ if(forwardResult==null ){ dict_list = null; } else{ }else{ forwardResultItem1 = forwardResult.deQueue(); if(forwardResultItem1==null ){ } else{ dict_list = forwardResultItem1.getDict_list(); showMatYoloForwardData(dict_list,frame); } } } private void showMatYoloForwardData(List dict_list, Mat frame) { if(dict_list.isEmpty()){ return; } List modelClassList = new ArrayList<>(); List elementVOList = new ArrayList<>(); for (int i = 0; i < dict_list.size(); i++) { MatYoloForwardData data = dict_list.get(i); String text = data.getClassName(); String[] pointResultSplit = data.getPointResult().split("\\|"); String[] pointResultSplit0 = pointResultSplit[0].split(","); String[] pointResultSplit1 = pointResultSplit[1].split(","); if(Double.parseDouble(pointResultSplit0[0])<0){ pointResultSplit0[0]="20"; } if(Double.parseDouble(pointResultSplit0[1])<0){ pointResultSplit0[1]="20"; } if(Double.parseDouble(pointResultSplit1[0])<0){ pointResultSplit1[0]="20"; } if(Double.parseDouble(pointResultSplit1[1])<0){ pointResultSplit1[1]="20"; } Double.parseDouble(pointResultSplit0[1])*0.67); Double.parseDouble(pointResultSplit1[1])*0.67); Integer.parseInt(pointResultSplit0[1])*0.6); Double.parseDouble(pointResultSplit0[1])*0.67); Point point1 = new Point(Double.parseDouble(pointResultSplit0[0]), Double.parseDouble(pointResultSplit0[1])); Point point2 = new Point(Double.parseDouble(pointResultSplit1[0]), Double.parseDouble(pointResultSplit1[1])); Integer.parseInt(pointResultSplit0[1])*0.6); Point point3 = new Point(Double.parseDouble(pointResultSplit0[0]), Double.parseDouble(pointResultSplit0[1])); Imgproc.rectangle(frame, point1, point2, new Scalar(255, 0, 0)); Imgproc.putText(frame, text, point3, Imgproc.FONT_HERSHEY_SIMPLEX, 1.5, new Scalar(255, 0, 0), 5); } if (bytesRead != -1) { String responseString = new String(buffer, 0, bytesRead); if(responseString.equals("{\"dict_list\":[]}") || responseString == null){ }else { try{ MatYoloForwardPoint pointResult = new Gson().fromJson(responseString, MatYoloForwardPoint.class); forwardResult.enQueue(pointResult); prevPointResult = pointResult; }catch (Exception e){ } } }else { break; }
nepoch
Ctrl+Alt+L idea
liu
package com.inspection_rn; public class MatYoloForwardData { /** * dict_list [{'classId': 0, 'confidence': 0.7602697610855103, 'pointResult': '94,158|129,213', 'className': 'person'}, * {'classId': 0, 'confidence': 0.7475467920303345, 'pointResult': '10,154|32,196', 'className': 'person'}] */ private Integer classId ; private String confidence ; private String pointResult ; private String className ; private Long modelId; private Long modelClassId; private Integer classNumber; public Integer getClassNumber() { return classNumber; } public void setClassNumber(Integer classNumber) { this.classNumber = classNumber; } public Long getModelId() { return modelId; } public void setModelId(Long modelId) { this.modelId = modelId; } public Long getModelClassId() { return modelClassId; } public void setModelClassId(Long modelClassId) { this.modelClassId = modelClassId; } public Integer getClassId() { return classId; } public void setClassId(Integer classId) { this.classId = classId; } public String getConfidence() { return confidence; } public void setConfidence(String confidence) { this.confidence = confidence; } public String getPointResult() { return pointResult; } public void setPointResult(String pointResult) { this.pointResult = pointResult; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } }
liu
package com.inspection_rn; import java.util.List; public class MatYoloForwardPoint { /** * dict_list [{'classId': 0, 'confidence': 0.7602697610855103, 'pointResult': '94,158|129,213', 'className': 'person'}, * {'classId': 0, 'confidence': 0.7475467920303345, 'pointResult': '10,154|32,196', 'className': 'person'}] */ private List dict_list; public List getDict_list() { return dict_list; } public void setDict_list(List dict_list) { this.dict_list = dict_list; } }
添加评论
搜索
作者

测试人员

BBS 一直在, 一感谢支持!
2023 测试内容
作者热门主题

预留信息

Nepoch
简单、易用、开放
一个综合性开放论坛
1
用户数
10
发帖数
手机可见,内容正在编写中,pc端可正常访问