3

我正在尝试用 C 开发一个小型聊天服务器。

对于一个简单的聊天服务器,

  • (传输端点)===(套接字)?
  • 我必须为每个客户端使用一个套接字,还是可以为多个客户端重复使用一个套接字?如果是这样,如何?
  • 有这样做的标准方法吗?
  • 有什么好的参考资料吗?

我可以看到一些示例实现吗?我必须使用 gcc 编译器和 c 语言来完成这项任务。

4

2 回答 2

4

You need one socket/client and no, you cannot reuse sockets. If you have to handle multiple clients you can:

  • create one thread per client and use blocking I/O (preferably with timeout).
  • create single threaded program and use demultiplexing with select/poll/epoll/kqueue and use non-blocking I/O.
  • use asynchronous I/O.

For C socket communication examples The Unix Network Programming book is probably the best source. It has ample of example programs and explanation.

于 2011-08-21T19:24:50.957 回答
2
  1. ( Transport endpoint ) === ( socket ) ?

NO. "Endpoint" means IP address with Port number. Socket presents one "Session" and session consists of two endpoints, local endpoint(IP, port) and remote endpoint(IP, port).

  1. Do i have to use one socket per client, or can I reuse a socket for multiple clients ? If so, how ?

One socket per one session. That means a server needs to create a new socket for each remote endpoint( client ). You can reuse socket when it's not in use anymore. Look for SO_REUSEADDR socket option.

  1. Is there a standard way of doing this ?

Not sure what you are asking. A standard way for chat service or for server/client model? For chat service, look for IRC. Server/Client programming model is well documented. You can Google it.

  1. Any good references available ?

http://beej.us/guide/bgnet/

Now I believe you understand what the error message means.

于 2011-08-21T19:29:27.350 回答