线程安全扫盲贴四中,改了异常消息发送的方法,把调用客户端发送消息改成了直接写消息到接收消息队列中,这样虽然接收消息线程池的线程飘红,但总能堵塞堵塞着执行完。为什么客户端并发socket请求会一直卡住了呢?我也不知道。
客户端发送socket的代码如下
/**
* 发送消息
* @param msg消息
* @param encoding 消息的编码格式
* @throws Exception
*/
public void sendMessage(final String msg,String encoding) throws ClientException{
SocketFactory sf = (SocketFactory) SocketFactory.getDefault();
String reqMsg = null;
Socket socket = null;
try {
reqMsg = new String(msg.getBytes(encoding),Encoding.UTF8);
socket = getSocket(sf);
BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream(),Encoding.UTF8));
PrintWriter tOut = new PrintWriter(bw);
log.debug("正在发送报文:"+reqMsg);
tOut.write(reqMsg);
tOut.println();
tOut.flush();
log.debug("客户端消息发送完毕!等待服务器端确认: "+reqMsg);
int totalBytesRcvd = 0;
int bytesRcvd = 0;
byte[] response = new byte["OK".length()];
InputStream in = socket.getInputStream();
while(totalBytesRcvd<response.length){
bytesRcvd = in.read(response, totalBytesRcvd, response.length-totalBytesRcvd);
if(bytesRcvd==-1){
throw new ClientException("发送失败,服务器端异常关闭了socket连接: "+reqMsg);
}
totalBytesRcvd = totalBytesRcvd+bytesRcvd;
}
//增加验证服务器端返回的消息,增加之前可以并发到5w
String rsp = new String(response,Encoding.UTF8);
log.debug("收到服务器端返回消息:"+rsp);
if(!rsp.equals("OK")){
throw new ClientException("发送失败,服务器端返回消息错误: "+rsp);
}
socket.close();
socket = null;
} catch (Exception e1) {
log.error(e1);
throw new ClientException("向服务器端发送报文失败"+reqMsg,e1);
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
log.error(e);
}
}
}
}
客户端的线程,并发1000个,总有最后2个就停住不执行了。
CyclicBarrier相当于一个拦截器,要指定的线程数都一起到了,再同时让他们run并发。
public class ClientRunnable implements Runnable{
private int index = -1;
private String msg = null;
private CyclicBarrier barrier = null;
public ClientRunnable(int i,CyclicBarrier barrier){
this.index=i;
this.msg = getMessage(i);
this.barrier = barrier;
}
public void run() {
IIPayrelayClient client = null;
try {
client = new Client();
barrier.await();
client.sendMessage(msg,"UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
}
}
这个问题下次再说,先下班了~~除了解决问题,就是下班最快乐咯^_^