[英]Client / Server C Connection
I am currently doing a client / server application in C that words over the internet.The server is to keep listening for new connections from the clients. 我目前正在使用C语言编写客户端/服务器应用程序,该应用程序通过Internet进行通信。服务器将继续侦听来自客户端的新连接。 Currently I am listening to cllients, but once a client connects, the server wont keep on listening for further clients.
目前,我正在听cllients,但是一旦客户端连接,服务器就不会继续监听其他客户端。 The following depicts the server side code to connect with a client:
下面描述了与客户端连接的服务器端代码:
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in sockaddr, cliaddr;
bzero(&sockaddr, sizeof(struct sockaddr_in));
bzero(&cliaddr, sizeof(struct sockaddr_in));
sockaddr.sin_family = AF_INET;
sockaddr.sin_addr.s_addr = INADDR_ANY;
sockaddr.sin_port = ntohs(atoi(argv[1]));
if(bind(sockfd, (struct sockaddr *) &sockaddr, sizeof(sockaddr)) <0) {
printf("error binding socket: %d\n", errno);
exit(1);
}
printf("binded to %d : %d\n", sockaddr.sin_addr.s_addr, htons(sockaddr.sin_port));
listen(sockfd,5);
socklen_t clilen = sizeof(cliaddr);
int newsockfd = accept(sockfd, (struct sockaddr *) &cliaddr, &clilen);
if (newsockfd < 0)
error("ERROR on accept");
printf("server connected to %d:%d\n", cliaddr.sin_addr.s_addr, htons(cliaddr.sin_port));
I am assuming i have to create some form of threads that will fork once a connection has been established. 我假设我必须创建某种形式的线程,这些线程将在建立连接后派生。 But i dont know how to implement it..
但是我不知道如何实现。
Any help is greatly appreciated 任何帮助是极大的赞赏
Following points might help: 以下几点可能会有所帮助:
You can collect the following Book to learn and understand how to develop concurrent server in C. It is hard to explain with examples various ways of writing concurrent server in the answer. 您可以收集以下本书,以学习和理解如何在C中开发并发服务器。在答案中很难用示例来解释编写并发服务器的各种方式。 The source codes of the examples in the book are downloadable so you can try them out even without the book (you will find in the same URL).
本书中示例的源代码可下载,因此即使没有本书也可以尝试使用它们(您将在同一URL中找到)。 Study the code and you will see how things work.
研究代码,您将了解事情的运作方式。
UNIX Network Programming, Volume 1, Second Edition: Networking APIs: Sockets and XTI UNIX网络编程,第1卷,第二版:网络API:套接字和XTI
This book covers almost all the things you want to know about socket programming. 本书涵盖了您想了解的有关套接字编程的几乎所有内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.