浅谈单例模式

 

       以前开发,很少用的设计模式,即使是最简单的单例模式。

       公司有一个项目要求实现socket客户端长连接,并实现自动重连。心想,如果是长连接的话,那么肯定你的客户端端口不能变。需要绑定端口。同时要没5秒发一次心跳。因为对象绑定,所以不能重新new一个channel。当时第一反应就是单例。可能会有别的更好的方法。可以限于技术有限。不说那么多,上关键代码。不好的地方请指点,往大家勿喷!

       

private static MySocketClient mySocketClient;
	private Selector selector;
	private SocketChannel sc ;
	
	
	private MySocketClient(String ip,int port){
		try {
			this.init(ip, port);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static MySocketClient getInstance(String ip,int port){
		if(mySocketClient == null){
			mySocketClient = new MySocketClient(ip,port);
		}
		return mySocketClient;
	}
	
	public void init(String ip,int port) throws Exception{
		try {
			selector = Selector.open();
			sc = SocketChannel.open();
			sc.socket().bind(new InetSocketAddress(Config.getLocalhostPort()));
			boolean b = sc.connect(new InetSocketAddress(InetAddress.getByName(ip), port));
			System.out.println("是否连接: "+b);
			sc.configureBlocking(false);
			sc.register(selector, SelectionKey.OP_READ);
			new Thread(new Listener(selector)).start();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void sendMessage(String msg){
		try {
			sc.write(ByteBuffer.wrap(msg.getBytes("gbk")));
		} catch (IOException e) {
			try {
				sc.close();
				mySocketClient = null;
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		}
	}

 

		Timer timer = new Timer();
		timer.schedule(new MyTask(), 1000*2, 1000*20);

 

public class MyTask extends TimerTask {

	@Override
	public void run() {
		MySocketClient myc = MySocketClient.getInstance(Config.getHostIp(), Config.getHostPort());
		myc.sendMessage("$PX\r\n");
	}

}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值