连接在UDP中被拒绝

时间:2015-05-29 20:45:46

标签: c unix udp

我正在使用UDP编写简单聊天,并且在向客户端重新发送消息时遇到错误。 错误:

  

sendto()::拒绝连接

我有单线程服务器和多线程客户端。两个线程在客户端,编写器和读取器中运行。 Writer工作正常并成功向服务器发送消息,服务器成功接收此消息。我尝试重新发送消息时遇到问题。 重新编写代码(服务器端):

printf("New local connection!\n");
struct sockaddr_un si_other;
char buf[MAX_MESSAGE_LENGTH];
struct msg messageReceived;
int len = sizeof(struct sockaddr_un);
rc =(int) recvfrom(localsocket,(void*)&messageReceived,sizeof(struct msg),0,(struct sockaddr *)&si_other,&len);
if(rc==-1)
{
    perror("recvfrom():");
}

rc = (int)sendto(localsocket,(void*)&messageReceived,sizeof(struct msg),0,(struct sockaddr *)&si_other,sizeof(si_other));
if(rc==-1)
{
    perror("sendto():");
}

从客户端重新编写代码:

作家帖子

while (fgets(messageToSend.buf, MAX_MESSAGE_LENGTH, stdin)!=NULL) {
    int rec = (int)sendto(sock, (void *)&messageToSend, sizeof(struct msg),0,(const struct sockaddr *)&serv,sizeof(struct sockaddr_in));
    if (rec == -1) {
        printf("Error while sending to server\n");
    }

读者线程

  printf("Reading from server initiated...\n");
int sock = (intptr_t)ptr;
struct msg receivedMessage;
FD_ZERO(&fds);
FD_SET(sock,&fds);
while (1) {
    printf("Waiting..\n");
    select(sock+1, &fds, NULL, NULL, NULL);
    if(FD_ISSET(sock,&fds))
    {
        int num = (int) recvfrom(sock, (void*)&receivedMessage, sizeof(struct msg),0,NULL,0);
        if (num > 0) {
            printf("Received message:%s\n", receivedMessage.buf);
        }
    }
}

0 个答案:

没有答案