Posts Tagged ‘客户端’
Netty4客户端断线重连机制
星期五, 五月 16th, 2014 1,841 views首先要了解一下Netty4客户端的运行机制,NettyClient.java代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | public class NettyClient { private final String host; private final int port; public NettyClient(String host, int port) { this.host = host; this.port = port; } public void run() throws Exception { // Configure the client. EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group) .channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<socketchannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast( //new LoggingHandler(LogLevel.INFO), new NettyHandler()); } }); // Start the client. ChannelFuture f = b.connect(host, port).sync(); // Wait until the connection is closed. f.channel().closeFuture().sync();//运行后会在这里阻塞 } finally { // Shut down the event loop to terminate all threads. group.shutdownGracefully(); } } } </socketchannel> |
当我们在主线程中执行 NettyClient(NettyClient).run()时,主线程会在 ChannelFuture f = b.connect(host, port).sync(); 这里阻塞,这是Netty4的一个新特性,我们利用这个特性即可创建一个定时器来实现断线重连的功能。
Android Socket TCP客户端简单实例
星期三, 四月 10th, 2013 1,571 views声明:本篇代码仅可用于android 4.0以下版本,4.0以后的版本中网络连接的代码不可在主线程运行。解决方法见后续几篇博客。
由于Android中可以使用java.io.*包和java.net.*包,所以此Demo的逻辑代码和JAVA版本的client没有区别,主要区别还是在于UI和一些接口函数上。
我们抛开UI从最基础的说起。
①建立连接:
先来看建立连接的核心代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | public class MainActivity extends Activity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); SocketAddress socketAddress = new InetSocketAddress("192.168.0.1", 2001); Socket socket = new Socket(); try { socket.connect(socketAddress,5000); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } ...... } |