android中recv()总是返回-1
我需要使用本机代码(在特定性)上通过Android上的插座在Localhost上发送几个字符串,但是我遇到了奇怪的问题-Recv()函数始终返回-1,Eerno告诉“重试!”
这是负责插座初始化和接收响应的代码,
void request() {
struct sockaddr_in sa;
memset(&sa, 0, sizeof(sa));
sa.sin_family = AF_INET;
//need to send string to localhost
inet_aton("127.0.0.1", &(sa.sin_addr));
int sock;
char res[7];
sock = socket(AF_INET, SOCK_STREAM, 0);
sa.sin_port = htons(27042);
int connection = connect(sock, (struct sockaddr *) &sa, sizeof sa);
if (connection != -1) { //connection >= 0
memset(res, 0, 7);
send(sock, "\x00", 1, NULL);
send(sock, "AUTH\r\n", 6, NULL);
usleep(100); // Give it some time to answer
int rec = recv(sock, res, 7, MSG_DONTWAIT);
// rec is always -1 and errno says "Try again!"
}
close(sock);
}
清单>清单
文件中有Internet
权限。
我试图将recv(袜子,Res,7,MSG_DONTWAIT)
零件放在循环中等待时,也许它会返回一些数据,但没有成功。也许我需要在send()之后打电话给flush()之类的东西?
有人知道在哪里可能有麻烦吗?
upd。此代码在一个Android应用程序(客户端)中运行,并试图将字符串发送到在同一设备(服务器)上运行的其他Android应用程序。
I need to send few strings on localhost via socket on android using native code (in C particularity) but I've faced weird problem - recv() function always returns -1 and eerno tells "Try again!"
Here is code responsible for initialization of socket and receiving response
void request() {
struct sockaddr_in sa;
memset(&sa, 0, sizeof(sa));
sa.sin_family = AF_INET;
//need to send string to localhost
inet_aton("127.0.0.1", &(sa.sin_addr));
int sock;
char res[7];
sock = socket(AF_INET, SOCK_STREAM, 0);
sa.sin_port = htons(27042);
int connection = connect(sock, (struct sockaddr *) &sa, sizeof sa);
if (connection != -1) { //connection >= 0
memset(res, 0, 7);
send(sock, "\x00", 1, NULL);
send(sock, "AUTH\r\n", 6, NULL);
usleep(100); // Give it some time to answer
int rec = recv(sock, res, 7, MSG_DONTWAIT);
// rec is always -1 and errno says "Try again!"
}
close(sock);
}
There is an INTERNET
permission in Manifest
file.
I've tried to put recv(sock, res, 7, MSG_DONTWAIT)
part in while loop to wait maybe it would return some data but no success. Maybe I need to call something like flush() after send()?
Does any one know where could be trouble?
UPD. This code runs in one android app (client) and tries to send string to other android app that runs on the same device (server).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
解决方案变得非常明显 - 当前的“服务器”版本无法处理“AUTH”消息,这就是“客户端”应用程序收到 -1 响应的原因。我尝试过旧版本,一切正常。
Solution became pretty obvious - current "server" version can't process "AUTH" message that is why "client" app receive -1 response. I've tried older version and everything worked fine.