我的应用包含一个连续循环。在循环的每次迭代中,通过Socket向服务器执行5到200个事务。
以前,我正在为每笔交易创建一个新的Socket。但是,我认为尽可能多地重用Socket会好得多。由于我在网上找不到任何重用套接字的正确方法的代码示例,我希望我以正确的方式完成它。
如果有人有任何改进此代码的建议,我们将不胜感激。
Socket socket = null;
boolean reuseSocket = true;
//This method is called between 5 and 150 times, every 10 seconds.
public String getViaSocket(String commandString) throws Exception {
StringBuilder sb = new StringBuilder();
OutputStream socketOutputStream = null;
InputStream socketInputStream = null;
try {
if (!reuseSocket || socket == null || socket.isClosed()) {
socket = new Socket(HTCS_IP_ADDRESS, HTCS_PORT_NUM);
}
if (reuseSocket) {
socket.setKeepAlive(true);
}
else {
socket.setKeepAlive(false);
}
socket.setSoTimeout(20 * 1000);
socket.setSoLinger(false, 0);
socketOutputStream = socket.getOutputStream();
socketOutputStream.write(commandString.getBytes());
socketOutputStream.flush();
socketInputStream = socket.getInputStream();
int b;
do {
b = socketInputStream.read();
sb.append((char)b);
}
while(!isEndOfResponse(b, sb));
return sb.toString();
}
finally {
try {
if (socketOutputStream != null) {
socketOutputStream.close();
}
}
catch(Exception e) {}
try {
if (socketInputStream != null) {
socketInputStream.close();
}
}
catch(Exception e) {}
try {
if (!reuseSocket && socket != null && !socket.isClosed()) {
socket.close();
}
}
catch(Exception e) {
e.printStackTrace();
}
}
}
Jim Garrison,EJP,Jarrod Roberson和ŁukaszLech,如果这是另一个问题的副本,你能告诉我你认为哪个问题重复了吗?