gpt4 book ai didi

c - RFComm-客户端while循环在服务器被杀死时不会结束

转载 作者:太空宇宙 更新时间:2023-11-04 10:13:34 24 4
gpt4 key购买 nike

我正在使用 RFComm 套接字。我有一个客户端循环,它在循环中读取和写入。我猜当服务器退出时,客户端也应该终止。但是客户端没有终止。它不打印“客户端循环退出”。我的代码如下-

    void* clientLoop(void* arg)

{
char* server_address = (char*)arg;
printf("\nserver address in clientLoop = %s\n",server_address);
struct sockaddr_rc addr = { 0 };
int s, status;
char gpsMessage[128];
int flag = true;

struct timeval tv;

// allocate a socket
s = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);

if(s<0) perror("socket error in client loop");
// set the connection parameters (who to connect to)
addr.rc_family = AF_BLUETOOTH;
addr.rc_channel = (uint8_t) 1;
str2ba( server_address, &addr.rc_bdaddr );

tv.tv_sec = 30; // 30 seconds
tv.tv_usec = 0; // microsecs, set to 0 (or ...)
setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv,sizeof(struct timeval));
// connect to server
status = connect(s, (struct sockaddr *)&addr, sizeof(addr));

if(status<0) perror("socket status error in client loop");

// send a message
if( status == 0 ) {
while(flag)
{
sleep(10);
printf("clientLoop did not exited\n");
prepareMessageToSend(gpsMessage);
status = write(s,gpsMessage , strlen(gpsMessage));
if(status == 0) flag=false;
status = read(s,gpsMessage, 128);
if(strcmp(gpsMessage,"Ring"))
{
printf("RING\n");
system("espeak -ven+f3 -k5 -s150 \"I've just picked up a fault in the AE35 unit\"");
}
if(status == 0) flag=false;
}
}

if( status < 0 ) perror("uh oh");
printf("clientLoop exited\n");
close(s);
//return s;
}

最佳答案

给套接字一个超时时间

struct timeval tv;
tv.tv_sec = 30; // 30 seconds
tv.tv_usec = 0; // microsecs, set to 0 (or ...)
setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv,sizeof(struct timeval));

如果无法在该时间内执行读取,则触发超时。

还有

 status = read(s,gpsMessage, 128);
// check status first, or if there is no ambiguity, check only the 4 first chars
if(strncmp(gpsMessage, "Ring", 4))

(以防消息设置不正确)

关于c - RFComm-客户端while循环在服务器被杀死时不会结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47496788/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com