[英]Can not read data from server using GCDAsyncSocket
I tried to connect to the server and send some information to the server(like username, password..), and the server send me back the ID (string type). 我试图连接到服务器并向服务器发送一些信息(如用户名,密码..),然后服务器发回给我ID(字符串类型)。 The problem is I can not get the ID.
问题是我无法获取ID。 Could anyone help me?
谁能帮助我? I am beginner in IOS coding.
我是IOS编码的初学者。 Thanks.
谢谢。
Here is the codes: 这是代码:
Then that function will call this function to connect the server: 然后该函数将调用此函数来连接服务器:
(void)logInCheck { asyncSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()]; NSError *error = nil; uint16_t port = serverPort; if (![asyncSocket connectToHost:serverIP onPort:port error:&error]) { DDLogError(@"Unable to connect to due to invalid configuration: %@", error); } else { DDLogVerbose(@"Connecting..."); [self passDataToServer]; } } //DataPassToServer is a NSString that hold my data (void)passDataToServer { NSData *requestData = [DataPassToServer dataUsingEncoding:NSUTF8StringEncoding]; [asyncSocket writeData:requestData withTimeout:-1.0 tag:0]; [asyncSocket readDataWithTimeout:-1 tag:0]; } //this function call successfully -(void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port { DDLogVerbose(@"socket:didConnectToHost:%@ port:%hu", host, port); } //this function call successfully (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag { DDLogVerbose(@"socket:didWriteDataWithTag:"); } //This function does not run !!! Nothing print out. (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag { DDLogVerbose(@"socket:didReadData:withTag:"); NSString *response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"ID = %@",response); [asyncSocket readDataWithTimeout:-1 tag:0]; }
I don't know about your server implementation but, most implementations would read up to the first newline character before processing the request. 我不知道您的服务器实现,但是,大多数实现在处理请求之前会读取第一个换行符。
So make sure that your [DataPassToServer dataUsingEncoding:NSUTF8StringEncoding]
includes a newline character ( "\\n"
) at the end. 因此,请确保您的
[DataPassToServer dataUsingEncoding:NSUTF8StringEncoding]
在末尾包含换行符( "\\n"
)。
Your code looks fine and works for me. 你的代码看起来很好,适合我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.