我有一个连接两台机器的系统,并且彼此之间收发信息。其中一台服务器使用RTSP协议向另一台服务器发送RTP语音数据包。我应该实现一个边缘情况,它需要满足以下条件;
当服务器关闭/崩溃时,套接字连接丢失。服务器可用时,我应该创建并连接一个新的套接字。在这方面,我删除了现有的套接字,创建了一个新的套接字(带有一个新的文件描述符)。但是即使服务器可用,它也不连接。
static int socket_new_try_connect( struct rtsp_session *s )
{
int flags;
int res = -1;
socklen_t slen;
struct hostent *he;
struct ast_hostent h;
while( res < 0 )
{
sleep(2);
if ((he=ast_gethostbyname("10.1.1.6", &h)) == NULL) {
log("socket_new_try_connect::ast_gethostbyname ERROR !\n");
continue;
}
memset(&s->sin, 0, sizeof(s->sin));
s->sin.sin_family = AF_INET;
s->sin.sin_port = htons(8554);
memmove(&s->sin.sin_addr, he->h_addr, sizeof(s->sin.sin_addr));
/* socket */
s->sock = socket(AF_INET, SOCK_STREAM, 0);
if (s->sock < 0) {
log("socket_new_try_connect::Unable to create RTSP session socket\n");
continue;
}
log("socket_new_try_connect::new RTSP socket is created. \n");
struct timeval timeout;
timeout.tv_sec = 5;
timeout.tv_usec = 0;
/*if(setsockopt(s->sock, SOL_SOCKET, SO_REUSEADDR, (char *)&timeout, sizeof(timeout)) < 0){
perror("setsockopt() SO_REUSEADDR");
close(s->sock);
continue;
}*/
if(setsockopt(s->sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout)) < 0){
log(LOG_ERROR, "setsockopt, EXIT FAILURE!\n");
perror("setsockopt()");
close(s);
continue;
}
if(setsockopt(s->sock, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout, sizeof(timeout)) < 0){
perror("setsockopt()");
close(s);
continue;
}
flags = fcntl(s->sock, F_GETFL);
fcntl(s->sock, F_SETFL, flags | O_NONBLOCK);
while(1)
{
res = connect(s->sock, (struct sockaddr *)&s->sin, sizeof(s->sin));
log(LOG_NOTICE, "socket_new_try_connect::connect RESULT : %d \n",res);
if(res < 0 && errno != EINPROGRESS) {
sleep(1);
continue;
}
else if( res < 0 )
{
log("socket_new_try_connect::Cannot connect to RTSP recording server. Error :%s\n", strerror(errno));
close(s->sock);
break;
}
else
{
log("socket_new:: SOCKET CONNECT IS SUCCESSFULL ! RESULT : %d \n",res);
return 1;
}
}
}
return 1;
}
使用上面的代码,我收到“正在运行”错误。崩溃后服务器再次可用时,我还保存了消息;
您能帮我详细说明问题吗?