Skip to content

Commit

Permalink
feat: 优化一下内存
Browse files Browse the repository at this point in the history
  • Loading branch information
yaming116 committed Oct 21, 2022
1 parent 0190d61 commit 04e14c5
Showing 1 changed file with 27 additions and 28 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
Expand All @@ -45,41 +46,34 @@ public SocketClientImpl(int port, Logger logger) {

@Override
public Object sendAndReceive(JSONObject jsonObject) throws SonicRespException {
int len = jsonObject.toJSONString().length();
ByteBuffer header = ByteBuffer.allocate(4);
header.put(intToByteArray(len), 0, 4);
header.flip();
ByteBuffer body = ByteBuffer.allocate(len);
body.put(jsonObject.toJSONString().getBytes(StandardCharsets.UTF_8), 0, len);
body.flip();
ByteBuffer total = ByteBuffer.allocate(len + 4);
total.put(header.array());
total.put(body.array());
total.flip();
byte[] data = jsonObject.toJSONString().getBytes(StandardCharsets.UTF_8);
byte[] header = intToByteArray(data.length);

synchronized (SocketClientImpl.class) {
try {
outputStream.write(total.array());
outputStream.write(header);
outputStream.write(data);
outputStream.flush();
byte[] head = new byte[4];
byte[] buffer = new byte[8192];
inputStream.read(head);
int headLen = toInt(head);
StringBuilder s = new StringBuilder();
ByteBuffer rData = ByteBuffer.allocate(headLen);
while (poco.isConnected() && !Thread.interrupted()) {
byte[] buffer = new byte[1024];

int realLen;
realLen = inputStream.read(buffer);
if (buffer.length != realLen && realLen >= 0) {
buffer = subByteArray(buffer, 0, realLen);
}
if (realLen >= 0) {
s.append(new String(buffer));
if (s.toString().getBytes(StandardCharsets.UTF_8).length == headLen) {
JSONObject re = JSON.parseObject(s.toString());
logger.info(re.toJSONString());
if (re.getString("id").equals(jsonObject.getString("id"))) {
return re.get("result");
} else {
throw new SonicRespException("id not found!");
}
rData.put(buffer, 0, realLen);

if (rData.position() == headLen) {
rData.flip();
String sData = new String(rData.array(),StandardCharsets.UTF_8 );
JSONObject re = JSON.parseObject(sData);
logger.info(sData);
if (re.getString("id").equals(jsonObject.getString("id"))) {
return re.get("result");
} else {
throw new SonicRespException("id not found!");
}
}
}
Expand Down Expand Up @@ -160,4 +154,9 @@ private int toInt(byte[] b) {
}
return res;
}
}

public static void main(String[] args) throws UnsupportedEncodingException {
System.out.printf("xx中文x".length()+ ",");
System.out.printf("xx中文x".getBytes(StandardCharsets.UTF_8).length+ "");
}
}

0 comments on commit 04e14c5

Please sign in to comment.