我制作了没有CLRFdata的简单客户端服务器,但是我给了lenght message self的消息头。这是我的代码:
此方法发送数据
- (void)sendMessage:(NSString *)message {
unsigned char lendata = [message length];
senddata = [NSMutableData dataWithBytes: &lendata length:sizeof(lendata)] ;
[senddata appendData:[message dataUsingEncoding:NSUTF8StringEncoding]];
[socket writeData:senddata withTimeout:-1 tag:0];
}
此方法从套接字lenght = 1字节读取数据,直到标头上的代码长。
- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
NSString *message = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
if(bheader){
cdata++;
if(cdata==2){
[data getBytes:&idata];
bheader = NO;
cdata=0;
cmessage = [[NSString alloc] initWithFormat:@""];
}
}
else{
if (message){
cmessage = [[NSString alloc]initWithFormat:@"%@%@",cmessage,message] ;
}
else
NSLog(@"Error converting received data into UTF-8 String");
cdata++;
if(cdata==idata) {
msgComplete=YES;
}
}
if (msgComplete) {
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:cmessage forKey:kNotificationMessage];
[notificationCenter postNotificationName:kNotification object:self userInfo:userInfo];
cmessage=@"";
msgComplete=NO;
bheader=YES;
cdata=0;
[cmessage release];
}
[sock readDataToLength:1 withTimeout:-1 tag:0];
}
和这个方法
- (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag {
[sock readDataToLength:1 withTimeout:-1 tag:0];
}
我成功从服务器发送数据和recv数据使用此代码, 我尝试使登录和服务器获取数据和通知,并使用此代码重新收到消息,但在此之后,当我再次发送消息时,我无法从服务器收回消息,但在TCPDUMP上,我看到任何消息发送到服务器和服务器响应消息?
任何人都可以修复我的代码问题吗? 感谢。