写了一个应用程序,但是不完善。请大侠们指点指点! 我的客户端是写成iPhone应用程序,socket是用CFsocket来写的。服务器是在Windows下,用MFC来写的。遵循的是TCP协议。现在已经测试通过了! 但有一个问题,就是当服务器断开之后,客户端并没有监听到服务器的断开,想问一下如何写个监听程序,当服务器断开时,客户端能及时退出,并返回重新连接的界面! 谢谢先~
连接图和发送图:
http://www.cocoachina.com/bbs/read.php?tid-48722.html
连接代码如下:
- (void) doConnect {
CFSocketContext CTX = {0, self, NULL, NULL, NULL};
//Create the socket of TCP
_socket = CFSocketCreate(kCFAllocatorDefault, PF_INET, SOCK_STREAM, IPPROTO_TCP, kCFSocketConnectCallBack, TCPServerConnectCallBack, &CTX);
//Create Error
if (NULL == _socket) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"Create socket error" delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil];
[alert show];
[alert release];
}
struct sockaddr_in Server_addr;
memset(&Server_addr, 0, sizeof(Server_addr));
Server_addr.sin_len = sizeof(Server_addr);
Server_addr.sin_family = AF_INET;
Server_addr.sin_addr.s_addr = htonl(0xc0a800c8L); //Only 192.168.2.202 allowed
Server_addr.sin_port = htons(70); //Only Port 70 allowed
//Server_addr.sin_addr.s_addr = inet_addr([connController.textField.text UTF8String]);
CFDataRef address = CFDataCreate(kCFAllocatorDefault, (UInt8 *)&Server_addr, sizeof(Server_addr));
//Connect the the server's socket
CFSocketConnectToAddress(_socket, address, -1);
CFRunLoopRef cfrl = CFRunLoopGetCurrent();
CFRunLoopSourceRef source = CFSocketCreateRunLoopSource(kCFAllocatorDefault, _socket, 0);
CFRunLoopAddSource(cfrl, source, kCFRunLoopCommonModes);
CFRelease(source);
CFRunLoopRun();
while (1) {
struct timeval tv;
tv.tv_usec = 0;
tv.tv_sec = 1;
select(-1, NULL, NULL, NULL, &tv);
}
}
发送代码如下:
- (void) sendMessage {
NSString *stringToSend = [sendController.textField.text stringByAppendingString:@"\n"];
const char *data = [stringToSend UTF8String];
send(CFSocketGetNative(_socket), data, strlen(data) + 1, 0);
NSRange endRange;
endRange.location = [sendController.textView.text length];
endRange.length = [stringToSend length];
sendController.textView.text = [sendController.textView.text stringByAppendingString:[@"Client: " stringByAppendingString:stringToSend]];
[sendController.textView scrollRangeToVisible:endRange];
sendController.textField.text = @"";
}
------解决方案--------------------
问题解决了~