我正在研究我的Android应用程序的iOS版本,该应用程序通过常规TCP连接不断向服务器发送一些二进制数据。虽然Java代码工作正常,但我在普通C中的代码没有 - 连接在第一批数据发送到服务器后中断。我设法使用CFNetwork框架重新实现Java解决方案,但是我的C代码仍然是一个问题......
C代码(错误检查和不感兴趣的代码被删除):
mSocket = socket(AF_INET, SOCK_STREAM, 0);
//...
connect(mSocket, (struct sockaddr *)&sin, sizeof(sin));
int keepalive = 1;
int res = setsockopt(mSocket, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive,
sizeof(int));
int set = 1;
setsockopt(mSocket, SOL_SOCKET, SO_NOSIGPIPE, (void *)&set, sizeof(int));
unsigned char buffer* = //...;
int ret = send(mSocket, buffer, bufferLen, 0); //handshake with server, runs fine
while(/*there is new data*/) {
buffer = new_data(); //some fake method
ret = send(mSocket, buffer, bufferLen, 0); //On the second iteration
//write returns -1
}
然而,这个基于CFNetwork的Objective-C代码工作得很好......
Objective-C代码:
CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault,
host,
port,
&readStream,
&writeStream);
CFWriteStreamOpen(mServerWriteStream);
while(/*there is new data*/) {
NSData* data = //....
int wroteBytes = CFWriteStreamWrite(mServerWriteStream, [data bytes], [data length]);
}
所以我很困惑我在C代码中做错了什么,并会欣赏任何提示
谢谢
答案 0 :(得分:2)
如果需要常规TCP连接,则需要使用此类协议创建套接字。而不是:
mSocket = socket(AF_INET, SOCK_STREAM, 0);
您应该将其创建为:
#include <netinet/in.h>
mSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
在我的系统上,IPPROTO_TCP被定义为6而不是0.我怀疑你有类似的东西。
答案 1 :(得分:0)
setsockopt()必须在connect()之前执行,否则会被忽略。