2016-08-05 3 views
-2

간단한 서버 코드를 작성하고 있습니다. 코드를 실행 한 후 "telnet localhost 8000"을 사용하여 서버에 연결하려고하는데 다음 오류가 발생합니다 : "외부 호스트에서 연결이 끊어졌습니다"그리고 서버가 닫힙니다. 이것은 내가 작성한 코드입니다.새 tcp 소켓 만들기 - 서버 쪽

void main(int argv,void * argc) 
{ 

//int socket(int af, int type, int protocol); 

    int listen_sckt; 
    int new_socket; 
    int addrlen; 
    struct sockaddr_in addr; 
/* 
#include <netinet/in.h> 

struct sockaddr_in { 
    short   sin_family; // e.g. AF_INET 
    unsigned short sin_port;  // e.g. htons(3490) 
    struct in_addr sin_addr;  // see struct in_addr, below 
    char    sin_zero[8]; // zero this if you want to 
}; 

struct in_addr { 
    unsigned long s_addr; // load with inet_aton() 
}; 

*/  

    listen_sckt = socket(AF_INET,SOCK_STREAM,0); 
    if(listen_sckt == -1){ 
     perror("SOCKET ERR\n"); 
     return; 
    } 
    printf("Socket succesfulyl opened\n"); 
{ 
/* 
binding a docket 
syntax: 
int bind(int s, struct sockaddr *addr, int addrlen); 
connect the socket to a logic port. 
so the other side will know where to "find" the other side 
*/ 
} 
    addr.sin_family = AF_INET;x` 
    addr.sin_addr.s_addr = INADDR_ANY; 
    addr.sin_port = htons(8000); 
    //binding command 
    if(-1 == bind(listen_sckt,(struct sockaddr*)&addr,sizeof(addr))){ 
     perror("BINDING ERR\n"); 
    } 
    printf("Binding succesfully done\n"); 

/* Listen() 
Before any connections can be accepted, the socket must be told to listen 
for connections and also the maximum number of pending connections using listen() 

Includes: 

#include <sys/socket.h> 

Syntax: 
int listen(int socket, int backlog); 
socket - the socket file descriptor 
backlog - the max number of pedding the socket will hold 

C source: 
*/ 

    listen(listen_sckt,2); 
/* 
To actually tell the server to accept a connection, you have to use the function accept() 

Includes: 

#include <sys/socket.h> 

Syntax: 

int accept(int s, struct sockaddr *addr, int *addrlen); 
*/ 
    addrlen = sizeof(struct sockaddr_in); 
    new_socket = accept(listen_sckt,(struct sockaddr*)&addr,&addrlen); 
    if(new_socket<0){ 
     perror("Accept ERR\n"); 
    }  
    printf("Acept success\n"); 
} 

고마워요.

+1

연결을 수락하고 메시지를 인쇄 한 후 서버가 아무 것도하지 않기 때문입니다. 서버 구현을 계속하십시오. 또한 리턴 값의 타입은 표준에 정의 된'int'이어야합니다. – MikeCAT

답변

3

연결을 수락하면 소켓을 포함한 모든 설명자가 닫히기 때문에 종료됩니다.

소켓으로 무엇인가하려면 accept 호출 후에해야합니다. 읽기/쓰기 루프가있는 것처럼.

그리고 모든 것이 돌아 다니기 때문에 프로그램이 이전 연결이 닫히면 새로운 연결을 받아 들일 수 있습니다.