客戶端:
導(dǎo)入頭文件:
#import <sys/socket.h>
#import <netinet/in.h>
#import <arpa/inet.h>
#import <unistd.h>
1. 創(chuàng)建連接
CFSocketContext sockContext = {0, // 結(jié)構(gòu)體的版本,必須為0
self, // 一個(gè)任意指針的數(shù)據(jù),可以用在創(chuàng)建時(shí)CFSocket對(duì)象相關(guān)聯(lián)。這個(gè)指針被傳遞給所有的上下文中定義的回調(diào)。
NULL, // 一個(gè)定義在上面指針中的retain的回調(diào), 可以為NULL
NULL, NULL};
CFSocketRef _socket = (kCFAllocatorDefault, // 為新對(duì)象分配內(nèi)存,可以為nil
PF_INET, // 協(xié)議族,如果為0或者負(fù)數(shù),則默認(rèn)為PF_INET
SOCK_STREAM, // 套接字類型,如果協(xié)議族為PF_INET,則它會(huì)默認(rèn)為SOCK_STREAM
IPPROTO_TCP, // 套接字協(xié)議,如果協(xié)議族是PF_INET且協(xié)議是0或者負(fù)數(shù),它會(huì)默認(rèn)為IPPROTO_TCP
kCFSocketConnectCallBack, // 觸發(fā)回調(diào)函數(shù)的socket消息類型,具體見Callback Types
TCPServerConnectCallBack, // 上面情況下觸發(fā)的回調(diào)函數(shù)
&sockContext // 一個(gè)持有CFSocket結(jié)構(gòu)信息的對(duì)象,可以為nil
);
if (_socket != nil) {
struct sockaddr_in addr4; // IPV4
memset(&addr4, 0, sizeof(addr4));
addr4.sin_len = sizeof(addr4);
addr4.sin_family = AF_INET;
addr4.sin_port = htons(8888);
addr4.sin_addr.s_addr = inet_addr([strAddress UTF8String]); // 把字符串的地址轉(zhuǎn)換為機(jī)器可識(shí)別的網(wǎng)絡(luò)地址
// 把sockaddr_in結(jié)構(gòu)體中的地址轉(zhuǎn)換為Data
CFDataRef address = CFDataCreate(kCFAllocatorDefault, (UInt8 *)&addr4, sizeof(addr4));
CFSocketConnectToAddress(_socket, // 連接的socket
address, // CFDataRef類型的包含上面socket的遠(yuǎn)程地址的對(duì)象
-1 // 連接超時(shí)時(shí)間,如果為負(fù),則不嘗試連接,而是把連接放在后臺(tái)進(jìn)行,如果_socket消息類型為kCFSocketConnectCallBack,將會(huì)在連接成功或失敗的時(shí)候在后臺(tái)觸發(fā)回調(diào)函數(shù)
);
CFRunLoopRef cRunRef = CFRunLoopGetCurrent(); // 獲取當(dāng)前線程的循環(huán)
// 創(chuàng)建一個(gè)循環(huán),但并沒有真正加如到循環(huán)中,需要調(diào)用CFRunLoopAddSource
CFRunLoopSourceRef sourceRef = CFSocketCreateRunLoopSource(kCFAllocatorDefault, _socket, 0);
CFRunLoopAddSource(cRunRef, // 運(yùn)行循環(huán)
sourceRef, // 增加的運(yùn)行循環(huán)源, 它會(huì)被retain一次
kCFRunLoopCommonModes // 增加的運(yùn)行循環(huán)源的模式
);
CFRelease(courceRef);
}
2. 設(shè)置回調(diào)函數(shù)
// socket回調(diào)函數(shù)的格式:
static void TCPServerConnectCallBack(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *data, void *info) {
if (data != NULL) {
// 當(dāng)socket為kCFSocketConnectCallBack時(shí),失敗時(shí)回調(diào)失敗會(huì)返回一個(gè)錯(cuò)誤代碼指針,其他情況返回NULL
NSLog(@"連接失敗");
return;
}
TCPClient *client = (TCPClient *)info;
// 讀取接收的數(shù)據(jù)
[info performSlectorInBackground:@selector(readStream) withObject:nil];
}
3. 接收發(fā)送數(shù)據(jù)
// 讀取接收的數(shù)據(jù)
- (void)readStream {
char buffer[1024];
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
while (recv(CFSocketGetNative(_socket), //與本機(jī)關(guān)聯(lián)的Socket 如果已經(jīng)失效返回-1:INVALID_SOCKET
buffer, sizeof(buffer), 0)) {
NSLog(@"%@", [NSString stringWithUTF8String:buffer]);
}
}
// 發(fā)送數(shù)據(jù)
- (void)sendMessage {
NSString *stringTosend = @"你好";
char *data = [stringTosend UTF8String];
send(SFSocketGetNative(_socket), data, strlen(data) + 1, 0);
}
服務(wù)器端:
CFSockteRef _socket;
CFWriteStreamRef outputStream = NULL;
int setupSocket() {
_socket = CFSocketCreate(kCFAllocatorDefault, PF_INET, SOCK_STREAM, IPPROTO_TCP, kCFSocketAcceptCallBack, TCPServerAcceptCallBack, NULL);
if (NULL == _socket) {
NSLog(@"Cannot create socket!");
return 0;
}
int optval = 1;
setsockopt(CFSocketGetNative(_socket), SOL_SOCKET, SO_REUSEADDR, // 允許重用本地地址和端口
(void *)&optval, sizeof(optval));
struct sockaddr_in addr4;
memset(&addr4, 0, sizeof(addr4));
addr4.sin_len = sizeof(addr4);
addr4.sin_family = AF_INET;
addr4.sin_port = htons(port);
addr4.sin_addr.s_addr = htonl(INADDR_ANY);
CFDataRef address = CFDataCreate(kCFAllocatorDefault, (UInt8 *)&addr4, sizeof(addr4));
if (kCFSocketSuccess != CFSocketSetAddress(_socket, address)) {
NSLog(@"Bind to address failed!");
if (_socket)
CFRelease(_socket);
_socket = NULL;
return 0;
}
CFRunLoopRef cfRunLoop = CFRunLoopGetCurrent();
CFRunLoopSourceRef source = CFSocketCreateRunLoopSource(kCFAllocatorDefault, _socket, 0);
CFRunLoopAddSource(cfRunLoop, source, kCFRunLoopCommonModes);
CFRelease(source);
return 1;
}
// socket回調(diào)函數(shù),同客戶端
void TCPServerAcceptCallBack(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *data, void *info) {
if (kCFSocketAcceptCallBack == type) {
// 本地套接字句柄
CFSocketNativeHandle nativeSocketHandle = *(CFSocketNativeHandle *)data;
uint8_t name[SOCK_MAXADDRLEN];
socklen_t nameLen = sizeof(name);
if (0 != getpeername(nativeSocketHandle, (struct sockaddr *)name, &nameLen)) {
NSLog(@"error");
exit(1);
}
NSLog(@"%@ connected.", inet_ntoa( ((struct sockaddr_in *)name)->sin_addr )):
CFReadStreamRef iStream;
CFWriteStreamRef oStream;
// 創(chuàng)建一個(gè)可讀寫的socket連接
CFStreamCreatePairWithSocket(kCFAllocatorDefault, nativeSocketHandle, &iStream, &oStream);
if (iStream && oStream) {
CFStreamClientContext streamContext = {0, NULL, NULL, NULL};
if (!CFReadStreamSetClient(iStream, kCFStreamEventHasBytesAvaiable,
readStream, // 回調(diào)函數(shù),當(dāng)有可讀的數(shù)據(jù)時(shí)調(diào)用
&streamContext)){
exit(1);
}
if (!CFReadStreamSetClient(iStream, kCFStreamEventCanAcceptBytes, writeStream, &streamContext)){
exit(1);
}
CFReadStreamScheduleWithRunLoop(iStream, CFRunLoopGetCurrent(), kCFRunLoopCommomModes);
CFWriteStreamScheduleWithRunLoop(wStream, CFRunLoopGetCurrent(), kCFRunLoopCommomModes);
CFReadStreamOpen(iStream);
CFWriteStreamOpen(wStream);
} else {
close(nativeSocketHandle);
}
}
}
// 讀取數(shù)據(jù)
void readStream(CFReadStreamRef stream, CFStreamEventType eventType, void *clientCallBackInfo) {
UInt8 buff[255];
CFReadStreamRead(stream, buff, 255);
printf("received: %s", buff);
}
void writeStream (CFWriteStreamRef stream, CFStreamEventType eventType, void *clientCallBackInfo) {
outputStream = stream;
}
main {
char *str = "nihao";
if (outputStream != NULL) {
CFWriteStreamWrite(outputStream, str, strlen(line) + 1);
} else {
NSLog(@"Cannot send data!");
}
}
// 開辟一個(gè)線程線程函數(shù)中
void runLoopInThread() {
int res = setupSocket();
if (!res) {
exit(1);
}
CFRunLoopRun(); // 運(yùn)行當(dāng)前線程的CFRunLoop對(duì)象
}
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無(wú)理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國(guó)服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡(jiǎn)單易用、服務(wù)可用性高、性價(jià)比高”等特點(diǎn)與優(yōu)勢(shì),專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場(chǎng)景需求。
網(wǎng)頁(yè)題目:IOS上的socket通信-創(chuàng)新互聯(lián)
網(wǎng)站URL:http://www.rwnh.cn/article2/dcicoc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供Google、網(wǎng)站營(yíng)銷、營(yíng)銷型網(wǎng)站建設(shè)、微信小程序、關(guān)鍵詞優(yōu)化、網(wǎng)站制作
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容