我正在尝试实现一种机制,客户端通过UDP将编码消息发送到服务器。收到此消息后,需要在服务器和客户端之间建立TCP连接。我正面临这个奇怪的问题,当我尝试与客户端建立TCP连接时,如果服务器事先从客户端收到UDP数据包,则connect()
在客户端失败。如果我尝试在没有任何UDP消息传递的情况下与客户端建立TCP连接,那么事情就可以了。我已经从服务器端和客户端附加了代码。
int sockfd, sockfd2, newsockfd, n;
char msg[1000];
sockaddr_in serverAddress, serverAddress2, clientAddress;
socklen_t len = sizeof(clientAddress);
/*create a socket*/
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
/*bind socket to an address*/
serverAddress.sin_family = AF_INET;
serverAddress.sin_addr.s_addr = INADDR_ANY;
serverAddress.sin_port = htons(12330);
bind(sockfd, (sockaddr *)&serverAddress, sizeof(sockaddr_in));
/*-----*/
n = recvfrom(sockfd, msg, 1000, 0, (sockaddr *)&clientAddress, &len);
sendto(sockfd, msg, strlen(msg), 0, (sockaddr *)&clientAddress, sizeof(clientAddress));
sockfd2 = socket(AF_INET, SOCK_STREAM, 0);
bzero(&serverAddress2,sizeof(serverAddress2));
serverAddress2.sin_family = AF_INET;
serverAddress2.sin_addr.s_addr = INADDR_ANY;
serverAddress2.sin_port = htons(12345);
bind(sockfd2, (sockaddr *)&serverAddress2, sizeof(serverAddress2));
listen(sockfd2, 10);
newsockfd = accept(sockfd2, (sockaddr *)&clientAddress, &len);
close(sockfd);
close(newsockfd);
close(sockfd2);
此外,bind()
,listen()
或socket()
函数均未发出错误。
客户端代码如下: -
/* create a UDP socket: SOCK_DGRAM */
sockfd = socket(AF_INET,SOCK_DGRAM,0);
printf("enter data ");
gets(sendline);
sendto(sockfd, sendline, strlen(sendline), 0, (struct sockaddr *) &servaddr, sizeof(servaddr));
/* wait for echo */
slen = sizeof(servaddr);
n = recvfrom(sockfd, recvline, STRLEN, 0, (struct sockaddr *) &servaddr, &slen);
close(sockfd);
wait(1000);
sockfd2=socket(AF_INET,SOCK_STREAM, 0);
client_addr.sin_family = AF_INET;
client_addr.sin_addr.s_addr=INADDR_ANY;
client_addr.sin_port = htons(12345);
bind(sockfd2, (struct sockaddr *) &client_addr, sizeof(client_addr));
connect(sockfd2,(struct sockaddr *) &servaddr,sizeof(servaddr));
此处的连接返回-1
。
答案 0 :(得分:2)
首先,如果connect()
返回-1
,请在errno
中查看<errno.h>
。这应该告诉你为什么它不开心。
其次,这可能与您在连接之前bind()
客户端套接字的事实有关,这看起来很奇怪。您通常只在服务器端bind()
打开套接字的端口。连接的客户端通常不绑定到端口,因此除非您特别需要它,否则请删除bind()
并重试。