「ios開発」tcp通信サンプルプログラム
#import <UIKit/UIKit.h>
#import “GCDAsyncSocket.h"
@interface ViewController : UIViewController {
GCDAsyncSocket *serverSocket;
NSMutableArray *allClientArray;
}
#import “ViewController.h"
#import “SendViewController.h"
@interface ViewController ()
@end
@implementation ViewController
– (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.title = @"メッセージを取得";
[self showNavItem];
[self createTcpSocket];
}
– (void) createTcpSocket {
allClientArray = [NSMutableArray array];
dispatch_queue_t dQueue = dispatch_queue_create(“My socket queue", NULL);
serverSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dQueue socketQueue:nil];
[serverSocket acceptOnPort:12345 error:nil];
}
– (void)socket:(GCDAsyncSocket *)sock didAcceptNewSocket:(GCDAsyncSocket *)newSocket {
NSString *ip = [newSocket connectedHost];
uint16_t port = [newSocket connectedPort];
NSLog(@"new socket [%@:%d] is %@", ip, port, newSocket);
[allClientArray addObject:newSocket];
[newSocket readDataWithTimeout:-1 tag:200];
NSString *s = @"Welcome";
NSData *data = [s dataUsingEncoding:NSUTF8StringEncoding];
[newSocket writeData:data withTimeout:60 tag:300];
}
– (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
NSString *ip = [sock connectedHost];
uint16_t port = [sock connectedPort];
NSString *s = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"received tcp [%@:%d] %@", ip, port, s);
NSString *s2 = [NSString stringWithFormat:@"データ:%@", s];
NSData *databack = [s2 dataUsingEncoding:NSUTF8StringEncoding];
[sock writeData:databack withTimeout:60 tag:400];
[sock readDataWithTimeout:-1 tag:200];
}
– (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err {
NSLog(@"lost connect %@", err);
[allClientArray removeObject:sock];
}
– (void) showNavItem {
UIBarButtonItem *sendMyself = [[UIBarButtonItem alloc] initWithTitle:@"send" style:UIBarButtonItemStylePlain target:self action:@selector(sendMyself)];
self.navigationItem.rightBarButtonItem = sendMyself;
}
– (void) sendMyself {
SendViewController *svc = [[SendViewController alloc] init];
[self.navigationController pushViewController:svc animated:YES];
}