1

如果标题具有误导性,我很抱歉。我真的想不出更好的了。这是我拥有的一些简单的套接字程序:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h> 
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/poll.h>
#include <iostream>

#define BACKLOG 10

void error(const char *msg)
{
    perror(msg);
    exit(1);
}


int main(int argc, char *argv[])
{
     if (argc < 2) {
         fprintf(stderr,"ERROR, no port provided\n");
         exit(1);
     }


     int sockfd = socket(AF_INET, SOCK_STREAM, 0);
     if (sockfd < 0) 
        error("ERROR opening socket");


     struct sockaddr_in serv_addr;
     bzero((char *) &serv_addr, sizeof(serv_addr));
     int portno = atoi(argv[1]);
     serv_addr.sin_family = AF_INET;
     serv_addr.sin_addr.s_addr = INADDR_ANY;
     serv_addr.sin_port = htons(portno);

     auto bindsuccess = bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));

     if (bindsuccess < 0)
        error("ERROR on binding");

     struct pollfd newPollFD[1];
     newPollFD[0].fd = sockfd;
     newPollFD[0].events = POLLIN;

     char buffer[256];
     bzero(buffer,256);

     listen(sockfd, BACKLOG);

     struct sockaddr_in cli_addr;
     socklen_t clilen = sizeof(cli_addr);

     int newsockfd;

     int rv = poll(newPollFD, 1, -1);

     if (rv == -1) {
        error("Error occured in Poll");
     }
     else {
        if (newPollFD[0].revents & POLLIN){

            newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
            if (newsockfd < 0) 
                error("ERROR on accept");

            int rwsuccess;

            rwsuccess = read(newsockfd,buffer,255);
            if (rwsuccess < 0)
                error("ERROR reading from socket");

            printf("Here is the message: %s\n",buffer);

            rwsuccess = write(newsockfd,"I got your message \n",18);

            if (rwsuccess < 0)
                error("ERROR writing to socket");
        }
     }

     close(newsockfd);
     close(sockfd);
     return 0; 
}

如果我使用端口号执行此代码,然后远程登录到该端口号,服务器会侦听,但只要我发送第一条消息,连接就会终止。我希望服务器继续收听和发送确认的次数与我从 telnet 发送消息的次数一样多。我该如何做到这一点?

提前致谢!

4

1 回答 1

3

奇怪的continue是,它是无关紧要的,并导致编译中断。(现在在您的编辑中更正了。)但是,您缺少一个for循环。并且,您应该添加一个检查是否read返回0.

        for (;;) {
          int rwsuccess;

          rwsuccess = read(newsockfd,buffer,255);
          if (rwsuccess < 0)
              error("ERROR reading from socket");
          if (rwsuccess == 0) break;

          printf("Here is the message: %s\n",buffer);

          rwsuccess = write(newsockfd,"I got your message \n",18);

          if (rwsuccess < 0)
              error("ERROR writing to socket");
        }
于 2012-07-12T22:59:45.943 回答