I have very simple server and chat but i cant figure out how to allow multiple clients.
(我有非常简单的服务器和聊天程序,但我不知道如何允许多个客户端。)
Most of code is what we get from teacher in school.(大部分代码是我们从学校老师那里得到的。)
int sock_desc = socket(AF_INET, SOCK_STREAM, 0);
char ccc = '
';
char *p_buf;
if (sock_desc == -1)
{
printf("cannot create socket!
");
return 0;
}
// configure socket
struct sockaddr_in server;
memset(&server, 0, sizeof(server));
server.sin_family = AF_INET;
// INADDR_ANY = 0.0.0.0
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(7777);
if (bind(sock_desc, (struct sockaddr*)&server, sizeof(server)) != 0)
{
printf("cannot bind socket!
");
close(sock_desc);
return 0;
}
// 20max connections
if (listen(sock_desc, 20) != 0)
{
printf("cannot listen on socket!
");
close(sock_desc);
return 0;
}
struct sockaddr_in client;
memset(&client, 0, sizeof(client));
socklen_t len = sizeof(client);
int temp_sock_desc = accept(sock_desc, (struct sockaddr*)&client, &len);
if (temp_sock_desc == -1)
{
printf("cannot accept client!
");
close(sock_desc);
return 0;
}
char buf[200];
int k;
int Second_sock_desc = socket(AF_INET, SOCK_STREAM, 0);
if (Second_sock_desc == -1)
{
printf("cannot create socket!
");
return 0;
}
// configure socket
struct sockaddr_in Second_client;
memset(&Second_client, 0, sizeof(Second_client));
Second_client.sin_family = AF_INET;
Second_client.sin_addr.s_addr = inet_addr("127.0.0.1");
Second_client.sin_port = htons(17777);
// connect socket
if (connect(Second_sock_desc, (struct sockaddr*)&Second_client, sizeof(Second_client)) != 0)
{
printf("cannot connect to server!
");
close(Second_sock_desc);
}
while(1)
{
// SEND RECV STUFF
}
close(temp_sock_desc);
close(sock_desc);
close(Second_sock_desc);
printf("server disconnected
");
return 0;
}
i found out that i need to make some while(1)
loop for accept()
function and recv/send stuff so i tried but it still wont work.
(我发现我需要对accept()
函数进行一些while(1)
循环并接收/发送内容,因此我尝试了一下,但仍然无法正常工作。)
(我的目标是在没有一些太高级的东西的情况下使其变得容易,但是我不知道该怎么做。)
I will be thankful for any help.(感谢您的帮助。)
ask by Kvikino translate from so