Home  >  Q&A  >  body text

objective-c - iOS 使用GCDAsyncSocket建立长连接发送消息

iOS 使用GCDAsyncSocket建立长连接发送消息,为什么没发送一条消息就要初始化GCDAsyncSocket一次,是不是我的代码哪里写错了

这个是发送消息按钮方法,当我GCDAsyncSocket初始化写到viewDidLoad,就服务器就接受不到消息

-(void)allPhotoAction:(UIButton *)btn{

//建立连接
NSString *host = @"192.168.0.199";
int port = 54111;
asyncsocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
asyncsocket.delegate = self;
NSError *error = nil;
if (![asyncsocket connectToHost:host onPort:port error:&error]) {
    //该方法异步
    GFFLog(@"%@",  @"连接服务器失败");
}

NSString *sendMessage = @"25";

[asyncsocket writeData:[sendMessage dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:1];

}

怪我咯怪我咯2746 days ago725

reply all(1)I'll reply

  • 给我你的怀抱

    给我你的怀抱2017-05-02 09:32:53

    It is recommended to look at more official examples.

    Call connectToHost The success returned does not mean that you are connected, it just means that there is nothing wrong with the host and port you entered. It has a callback method for successful connection, and call writeData after that method. To maintain a long connection, read must be called after each write/receive to keep the socket listening.

    reply
    0
  • Cancelreply