并发Socket消息发送

线程安全扫盲贴四中,改了异常消息发送的方法,把调用客户端发送消息改成了直接写消息到接收消息队列中,这样虽然接收消息线程池的线程飘红,但总能堵塞堵塞着执行完。为什么客户端并发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();
		}
	}

}

 

这个问题下次再说,先下班了~~除了解决问题,就是下班最快乐咯^_^

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值