如果標題有誤導性,我很抱歉。我無法真正想到一個更好的。下面是一些簡單的套接字程序,我有:調查TCP套接字空閒偵聽
#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;
}
如果我和端口號執行該代碼,然後遠程登錄到該端口號,服務器監聽的,但只要我把我的第一個消息,連接終止。我希望服務器繼續監聽併發送確認消息,正如我從遠程登錄發送消息一樣多次。我如何實現這一目標?
在此先感謝!
我不確定代碼是如何編譯的,就像'continue'語句和沒有循環一樣。 – 2012-07-12 22:59:08
這是我的一個愚蠢的錯誤。發佈前我正在嘗試一些東西。忘了刪除它。真誠的歉意。 – 2012-07-12 23:01:28
這聽起來像你在正確的軌道上,因爲'continue'需要一個循環,並且循環就是你想要的。 – 2012-07-13 05:11:03