学习iOS也有一段时间了。也在试着用iOS来写项目,感谢各路大神的帮助,就不一一@了。本文只是记载本人的学习过程。
---------------------学如逆水行舟不进则退。
1我也只是试一试,如有错误还请各位指出点评
越来越多的应用开始有了即时通讯的功能,我们就可以用scoket来实现
1.框架AsyncSocket
引入头文件
AsyncSocket.h
2.直接贴出代码了
//
// RootViewController.h
// socket测试一下感觉简单
//
// Created by黄权浩 on 14-11-30.
// Copyright (c) 2014年黄权浩. All rights reserved.
//
#import <UIKit/UIKit.h>
//聊天
#import "AsyncSocket.h"
@interface RootViewController : UIViewController{
AsyncSocket *client;
}
@property (nonatomic, retain) AsyncSocket *client;
@property (weak, nonatomic) IBOutlet UILabel *outputMsg;
@property (weak, nonatomic) IBOutlet UITextField *inputMsg;
- (int) connectServer:(NSString *)hostIP port:(int)hostPort;
- (void) showMessage:(NSString *) msg;
- (IBAction) sendMsg;
- (IBAction) reConnect;
@end
.m
//
// RootViewController.m
// socket测试一下感觉简单
//
// Created by黄权浩 on 14-11-30.
// Copyright (c) 2014年黄权浩. All rights reserved.
//
#import "RootViewController.h"
//GCD
#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_PORT1 8080
@interface RootViewController ()
@end
@implementation RootViewController
@synthesize inputMsg, outputMsg;
@synthesize client;
/*********
哈哈。scoket
}
*********/
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
[self connectServer:HOST_IP port:HOST_PORT1];
//监听读取
}
// 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(@"%ld %@", (long)[err code], [err localizedDescription]);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[@"Connection failed to host "
stringByAppendingString:hostIP]
message:[[[NSString alloc]initWithFormat:@"%ld",(long)[err code]] stringByAppendingString:[err localizedDescription]]
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
//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_PORT1];
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(@"%@",content);
NSData *data = [content dataUsingEncoding:NSISOLatin1StringEncoding];
[client writeData:data withTimeout:-1 tag:0];
//继续监听读取
[client readDataWithTimeout:-1 tag:0];
}
#pragma mark socket uitl
- (void) showMessage:(NSString *) msg{
UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"Alert!"
message:msg
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
}
#pragma mark socket delegate
//超时设置
- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port{
[client readDataWithTimeout:-1 tag:0];
}
//错误
- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err
{
NSLog(@"Error");
}
//连接失败
- (void)onSocketDidDisconnect:(AsyncSocket *)sock
{
NSString *msg = @"Sorry this connect is failure";
[self showMessage:msg];
client = nil;
}
- (void)onSocketDidSecure:(AsyncSocket *)sock{
}
//超时处理
- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
NSString* aStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"Hava received datas is :%@",aStr);
self.outputMsg.text = aStr;
[client readDataWithTimeout:-1 tag:0];
}
@end