我正在创建服务器/ clinet,但我遇到了问题。如果我是第一次启动服务器和客户端,则everthing工作正常。然后我关闭它们,我在几秒钟后再次启动它们,我收到e"连接被拒绝"客户端出错。我总是先启动服务器,然后是客户端。这是代码。 DoLogin是一个简单的函数,有2次读取和2次写入。这段代码有什么问题?
server.c
int main(){
int ds_sock;
struct sockaddr_in my_addr;
ds_sock=socket(AF_INET,SOCK_STREAM,0);
memset(&my_addr,0,sizeof(my_addr));
my_addr.sin_family=AF_INET;
my_addr.sin_port=htons(25000);
my_addr.sin_addr.s_addr=INADDR_ANY;
if(bind(ds_sock,(struct sockaddr *)&my_addr,sizeof(my_addr))<0){
printf("Error in bind");
}
listen(ds_sock,2);
int ds_sock_acc;
struct sockaddr_in addr;
size_t sin_size = sizeof(struct sockaddr_in);
if((ds_sock_acc=accept(ds_sock,(struct sockaddr *)&addr,&sin_size))<1){
printf("Error accept");
}
printf("Connected\n");
char *usr = DoLogin(ds_sock_acc);
printf("%s is connected\n",usr);
close(ds_sock_acc);
close(ds_sock);
return 0;
}
client.c
int main(){
int ds_sock;
ds_sock = socket(AF_INET, SOCK_STREAM,0);
int ret;
struct sockaddr_in Eaddr;
Eaddr.sin_family = AF_INET;
Eaddr.sin_port = htons(25000);
Eaddr.sin_addr.s_addr=inet_addr("127.0.0.1");
ret = connect(ds_sock,(struct sockaddr *)&Eaddr,sizeof(Eaddr));
if(ret==-1){
printf("Error connect");
perror("error:");
exit(EXIT_FAILURE);
}
printf("Connect OK\n");
char *usr = DoLogin(ds_sock);
printf("Logged in as %s\n",usr);
close(ds_sock);
return 0;
}
答案 0 :(得分:3)
O / S通常会阻止在前一个套接字关闭后在同一端口上重新创建一个侦听套接字,以防止最初发往原始套接字的消息被传递给新套接字。
要覆盖此行为,您需要setsockopt
SO_REUSEADDR
选项(在服务器端):
int optval = 1;
setsockopt(ds_sock, SO_REUSEADDR, &optval, sizeof(optval));
[错误检查省略]