IOS AsyncSocket and Java Netty simple socket usage

Source: Internet
Author: User

IOS AsyncSocket and Java Netty simple socket usage
In the past two days, I have taken a brief look at the Netty framework. Netty provides asynchronous, event-driven network application frameworks and tools to quickly develop high-performance, high-reliability network servers and client programs. That is to say, Netty is a NIO-based client and server-side programming framework. Using Netty ensures that you can quickly and easily develop a network application, such as a customer who implements a certain protocol, server applications. Netty simplifies and streamlined the programming and development process of network applications, such as TCP and UDP socket service development. Therefore, according to the official introduction, AsyncSocket is a network library based on CFSocket and CFStream encapsulation of TCP/IP socket. It provides asynchronous operations and local cocoa delegate support. Key features are as follows: 1. Optional timeout of the queue for non-blocking read and write. For example, if you tell it the read/write content, it will notify you when it is completed. 2. Automatic receipt of socket. If you tell it to accept the connection, it will create a new instance for each connection for you to call. You can also choose to disconnect immediately. 3. Support for Delegate. The delegate method contains errors, connections, receiving, complete read/write, progress, and disconnection. 4. Run-loop is not based on threads. Although you can use it in the main thread or child thread, it is necessary. It uses the nsunloop to asynchronously call the delegate method. The delegate method includes a socket parameter that allows you to differentiate multiple instances. 5. Self-wrapped in a class. You do not need to operate the stream or Socket. It will handle it by itself. 6. TCP streams based on IPv4 and IPv6 are supported. Github address: Of course, the first step is to download and install Netty and AsyncSocket. Step 2: Create a server: 1. HelloServer

Package com. nettypro. io; import io. netty. bootstrap. serverBootstrap; import io. netty. channel. channelFuture; import io. netty. channel. channelInitializer; import io. netty. channel. channelOption; import io. netty. channel. eventLoopGroup; import io. netty. channel. nio. nioEventLoopGroup; import io. netty. channel. socket. socketChannel; import io. netty. channel. socket. nio. nioServerSocketChannel; public class HelloServer {/** create server listening port */private static final int portNumber = 8080; public static void main (String [] args) throws InterruptedException {EventLoopGroup boosGroup = new NioEventLoopGroup (); EventLoopGroup workerGroup = new NioEventLoopGroup (); try {ServerBootstrap bootstrap = new ServerBootstrap (); bootstrap. group (boosGroup, workerGroup); bootstrap. channel (NioServerSocketChannel. class); bootstrap. childHandler (new HelloServerInitializer ()). childOption (ChannelOption. SO_KEEPALIVE, true); // (6); // The server binding port listens to ChannelFuture channelFuture = bootstrap. bind (portNumber ). sync (); // the listener server closes the listener channelFuture. channel (). closeFuture (). sync ();} finally {boosGroup. shutdownGracefully (); workerGroup. shutdownGracefully ();}}}

 

2. HelloServerInitializer
Package com. nettypro. io; import io. netty. channel. channelInitializer; import io. netty. channel. channelPipeline; import io. netty. channel. socket. socketChannel; import io. netty. handler. codec. delimiterBasedFrameDecoder; import io. netty. handler. codec. delimiters; import io. netty. handler. codec. string. stringDecoder; import io. netty. handler. codec. string. stringEncoder; public class HelloServerInitializer extends ChannelInitializer <SocketChannel >{@ Override protected void initChannel (SocketChannel arg0) throws Exception {// TODO Auto-generated method stub // ChannelPipeline can be understood as a message transmission channel that has a ChannelPipeline channelPipeline = arg0.pipeline (); // Add a function for the channel // string decoding code channelPipeline. addLast ("decoder", new StringDecoder (); channelPipeline. addLast ("encoder", new StringEncoder (); // Add the autonomous logic channelPipeline. addLast (new HelloServerHandler ());}}

 

3. HelloServerHandler
Package com. nettypro. io; import java.net. inetAddress; import java.net. unknownHostException; import java. util. export; import javax. xml. crypto. data; import io. netty. buffer. byteBuf; import io. netty. channel. channelHandlerContext; import io. netty. channel. extends; public class HelloServerHandler extends SimpleChannelInboundHandler <String >{@ Override protected void channelRead0 (ChannelHandlerContext arg0, String arg1) {// TODO Auto-generated method stub System. out. println (arg0.channel (). remoteAddress () + "---- channelRead0"); // print System directly when a message is received. out. println (arg0.channel (). remoteAddress () + "MSG:" + arg1); // reply message response = new response (System. in); String msgString = callback. nextLine () + "\ n"; System. out. println (arg0.channel (). remoteAddress () + "msgString:" + msgString); arg0.writeAndFlush (msgString);}/*** called when channel is activated */@ Override public void channelActive (ChannelHandlerContext ctx) {// TODO Auto-generated method stub System. out. println (ctx. channel (). remoteAddress () + "---- Acrive"); try {ctx. writeAndFlush ("Welcome you to here" + InetAddress. getLocalHost (). getHostName ();} catch (UnknownHostException e) {e. printStackTrace ();}}}

 

Step 3: Create a client:
# Import "ViewController. h "# import <sys/socket. h> # import <netinet/in. h> # import <arpa/inet. h> # import <unistd. h> # import "AsyncSocket. h "@ interface ViewController () <AsyncSocketDelegate> @ property (nonatomic, retain) NSTimer * heartTimer; @ property (nonatomic, retain) AsyncSocket * ay; @ property (strong, nonatomic) IBOutlet UITextField * msgTF; @ property (strong, nonatomic) IBOutlet UITextView * showTV; @ end @ imp Lementation ViewController-(void) viewDidLoad {[super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. self. ay = [[AsyncSocket alloc] initWithDelegate: self]; [self. ay connectToHost: @ "localhost" onPort: 8080 error: nil]; self. ay. delegate = self; NSString * msg = @ "HelloNetty"; [self. ay writeData: [msg dataUsingEncoding: NSUTF8StringEncoding] withTimeout: 10.0f tag: 1 01]; [self. ay readDataWithTimeout:-1 tag: 0];}-(void) didReceiveMemoryWarning {[super didreceivemorywarning]; // Dispose of any resources that can be recreated .} -(IBAction) sendAction :( UIButton *) sender {if (self. msgTF. text. length! = 0) {self. showTV. text = [NSString stringWithFormat: @ "% @ \ n client: % @", self. showTV. text, self. msgTF. text]; [self. ay writeData: [self. msgTF. text dataUsingEncoding: NSUTF8StringEncoding] withTimeout: 10.0f tag: 101]; [self. ay readDataWithTimeout:-1 tag: 0]; self. msgTF. text = nil ;}# pragma mark # pragma mark -- AsyncSocketDelegate --- (void) onSocket :( AsyncSocket *) sock didReadData :( NSData *) data withTag :( long) tag {NSString * msg = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]; NSLog (@ "msg ----- % @", msg); if (self. showTV. text. length = 0) {self. showTV. text = [NSString stringWithFormat: @ "server: % @", msg];} else {self. showTV. text = [NSString stringWithFormat: @ "% @ \ n server: % @", self. showTV. text, msg];} [self. ay readDataWithTimeout:-1 tag: 0];}-(void) onSocket :( AsyncSocket *) sock didWriteDataWithTag :( long) tag {[self. ay readDataWithTimeout:-1 tag: 0];}-(void) onSocket :( AsyncSocket *) sock didConnectToHost :( NSString *) host port :( UInt16) port {NSLog (@ "didConnectToHost % @ ------ % d", host, port); [self. ay readDataWithTimeout:-1 tag: 0];}-(void) onSocket :( AsyncSocket *) sock didReadPartialDataOfLength :( NSUInteger) partialLength tag :( long) tag {NSLog (@ "Received bytes: % lu ", (unsigned long) partialLength);} @ end

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.