search

Home  >  Q&A  >  body text

objective-c - iOS uses GCDAsyncSocket to establish a long connection to send messages

iOS uses GCDAsyncSocket to establish a long connection to send messages. Why does GCDAsyncSocket need to be initialized once before sending a message? Is there something wrong with my code?

This is the button method to send a message. When I initialize GCDAsyncSocket and write to viewDidLoad, the server cannot receive the message

-(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];

}

怪我咯怪我咯2805 days ago773

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