iOS Socket第三方開源類庫 AsyncSocket
阿新 • • 發佈:2018-12-20
假如你也是一個java程式設計師,而你又不是很懂Socket。
下面我的這篇文章也許能幫助你一些。
首先我們寫好上面文章中的server端。
下面我們可以訪問一下下面的地址:
這是一個開源框架。呵,不知道拿到自己程式中使用是否涉及侵權。
但是這句話“The CocoaAsyncSocket project is in the public domain.”是我有信心使用它們的原始碼,否則只能自己用c來寫了,或者使用CFSocket、CFNetwork等類自己來寫了。不過也無妨,應在在使用執行緒的情況下,我們也是可以實現的。
總之,為了開發的便捷,我使用了AsyncSocket這個類,這樣可以非同步通訊。
我們AsyncSocket.h和AsyncSocket.m到我們的專案中,並且匯入CFNetwork.framework。這樣基本準備工作就做好了。
下面提供我的應用中的程式碼以及介面圖:
Socketdemoviewcontroller.h程式碼- //
- // SocketDemoViewController.h
- // SocketDemo
- //
- // Created by xiang xiva on 10-7-10.
- // Copyright 2010 __MyCompanyName__. All rights reserved.
- //
- #import <UIKit/UIKit.h>
- #import "AsyncSocket.h"
- #define SRV_CONNECTED 0
- #define SRV_CONNECT_SUC 1
- #define SRV_CONNECT_FAIL 2
- #define HOST_IP @"192.168.110.1"
- #define HOST_PORT 8080
- @interface SocketDemoViewController : UIViewController {
- UITextField *inputMsg;
- UILabel *outputMsg;
- AsyncSocket *client;
- }
- @property (nonatomic, retain) AsyncSocket *client;
- @property (nonatomic, retain) IBOutlet UITextField *inputMsg;
- @property (nonatomic, retain) IBOutlet UILabel *outputMsg;
- - (int) connectServer: (NSString *) hostIP port:(int) hostPort;
- - (void) showMessage:(NSString *) msg;
- - (IBAction) sendMsg;
- - (IBAction) reConnect;
- - (IBAction) textFieldDoneEditing:(id)sender;
- - (IBAction) backgroundTouch:(id)sender;
- @end
- //
- // SocketDemoViewController.m
- // SocketDemo
- //
- // Created by xiang xiva on 10-7-10.
- // Copyright 2010 __MyCompanyName__. All rights reserved.
- //
- #import "SocketDemoViewController.h"
- @implementation SocketDemoViewController
- @synthesize inputMsg, outputMsg;
- @synthesize client;
- /*
- // The designated initializer. Override to perform setup that is required before the view is loaded.
- - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
- self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
- if (self) {
- // Custom initialization
- }
- return self;
- }
- */
- /*
- // Implement loadView to create a view hierarchy programmatically, without using a nib.
- - (void)loadView {
- }
- */
- // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- - (void)viewDidLoad {
- //[super viewDidLoad];
- [self connectServer:HOST_IP port:HOST_PORT];
- //監聽讀取
- }
- // Override to allow orientations other than the default portrait orientation.
- - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
- return YES;
- }
- - (void)didReceiveMemoryWarning {
- // Releases the view if it doesn't have a superview.
- [super didReceiveMemoryWarning];
- // Release any cached data, images, etc that aren't in use.
- }
- - (void)viewDidUnload {
- self.client = nil;
- // Release any retained subviews of the main view.
- // e.g. self.myOutlet = nil;
- }
- - (int) connectServer: (NSString *) hostIP port:(int) hostPort{
- if (client == nil) {
- client = [[AsyncSocket alloc] initWithDelegate:self];
- NSError *err = nil;
- //192.168.110.128
- if (![client connectToHost:hostIP onPort:hostPort error:&err]) {
- NSLog(@"%@ %@", [err code], [err localizedDescription]);
- UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[@"Connection failed to host "
- stringByAppendingString:hostIP]
- message:[[[NSString alloc]initWithFormat:@"%@",[err code]] stringByAppendingString:[err localizedDescription]]
- delegate:self
- cancelButtonTitle:@"OK"
- otherButtonTitles:nil];
- [alert show];
- [alert release];
- //client = nil;
- return SRV_CONNECT_FAIL;
- } else {
- NSLog(@"Conectou!");
- return SRV_CONNECT_SUC;
- }
- }
- else {
- [client readDataWithTimeout:-1 tag:0];
- return SRV_CONNECTED;
- }
- }
- - (IBAction) reConnect{
- int stat = [self connectServer:HOST_IP port:HOST_PORT];
- switch (stat) {
- case SRV_CONNECT_SUC:
- [self showMessage:@"connect success"];
- break;
- case SRV_CONNECTED:
- [self showMessage:@"It's connected,don't agian"];
- break;
- default:
- break;
- }
- }
- - (IBAction) sendMsg{
- NSString *inputMsgStr = self.inputMsg.text;
- NSString * content = [inputMsgStr stringByAppendingString:@"\r\n"];
- NSLog(@"%a",content);
- NSData *data = [content dataUsingEncoding:NSISOLatin1StringEncoding];
- [client writeData:data withTimeout:-1 tag:0];
- //[data release];
- //[content release];
- //[inputMsgStr release];
- //繼續監聽讀取
- //[client readDataWithTimeout:-1 tag:0];
- }
- #pragma mark -
- #pragma mark close Keyboard
- - (IBAction) textFieldDoneEditing:(id)sender{
- [sender resignFirstResponder];
- }
- - (IBAction) backgroundTouch:(id)sender{
- [inputMsg resignFirstResponder];
- }
- #pragma mark socket uitl
- - (void) showMessage:(NSString *) msg{
- UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"Alert!"
- message:msg
- delegate:nil