fork(). を使用して複数のクライアントを同時に処理するためのソケット プログラミング サーバーを作成しようとしています。しかし、適切に実装することはできません。私が直面している問題は、1) アドレス バインドの問題 2) 親プロセスと子プロセスの処理方法の問題 3) サーバー プログラムの終了方法、つまり..コンソールに戻る方法です。複数のクライアントサーバー用の私のコード。
#include<signal.h>
#include<stdio.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<string.h>
#include<sys/types.h>
#include<stdlib.h>
int main()
{
struct sockaddr_in myaddr ,clientaddr;
int sockid,newsockid;
sockid=socket(AF_INET,SOCK_STREAM,0);
memset(&myaddr,'0',sizeof(myaddr));
myaddr.sin_family=AF_INET;
myaddr.sin_port=htons(8888);
myaddr.sin_addr.s_addr=inet_addr("127.0.0.1");
if(sockid==-1)
{
perror("socket");
}
int len=sizeof(myaddr);
if(bind(sockid,( struct sockaddr*)&myaddr,len)==-1)
{
perror("bind");
}
if(listen(sockid,10)==-1)
{
perror("listen");
}
int pid,new;
static int counter=0;
for(;;)
{ a:
new =accept(sockid,(struct sockaddr *)&clientaddr,&len);
if(pid=fork()==-1)
{
close(new);
continue;
}
else if(pid>0)
{
counter++;
//wait();
goto a;
printf("here2");
//close(new);
continue;
}
else if(pid==0)
{
counter++;
printf("here 1");
send(new,"hi",100,0);
send(new,(char *) &counter,1,0);
//kill(pid,SIGKILL);
//close(new);
}
}
printf("here3");
close(sockid);
return 0;
}
ここに簡単なクライアントプログラムがあります
#include<stdio.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<string.h>
#include<sys/types.h>
int main()
{
struct sockaddr_in myaddr ,serveraddr;
int sockid;
sockid=socket(AF_INET,SOCK_STREAM,0);
memset(&myaddr,'0',sizeof(myaddr));
myaddr.sin_family=AF_INET;
myaddr.sin_port=htons(8888);
myaddr.sin_addr.s_addr=inet_addr("127.0.0.1");
if(sockid==-1)
{
perror("socket");
}
int len=sizeof(myaddr);
if(connect(sockid,(const struct sockaddr*)&myaddr,len)==-1)
{
perror("connect");
}
fprintf(stdout,"Client Online....");
char s[10000];
//gets(s);
//send(sockid,s,10000,0);
recv(sockid,&s,10000,0);
fprintf(stdout,"Server says....");
puts(s);
recv(sockid,&s,10000,0);
fprintf(stdout,"Server says....");
puts(s);
sleep(10);
close(sockid);
return 0;
}
誰かが私が間違っていることと、それを行う正しい方法を教えてください..? どんな助けでも大歓迎です...