TCP服务器用C听多张客户一次 [英] TCP server listen to mulitple clients at once in C

查看:74
本文介绍了TCP服务器用C听多张客户一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经写C code代表一个TCP服务器在同一时间听一个客户端..但我有困难搞清楚怎样才能得到服务器在同一时间收听多个客户端。

I have written C code for a TCP server to listen to one client at a time.. but I'm having difficulty figuring out how I can get the server to listen to multiple clients at one time.

有没有一个很好的教程或例子解释这个任何人知道吗?

Does any one know of a good tutorial or example explaining this?

谢谢!

推荐答案

有多种方式来实现这一点,其中一些是:

There are a number of ways to achieve this, some of which are:


  • 使用选择来对一组文件描述符基本上等到其中一个是准备读或写。

  • 使用线程,如的pthreads ,以手关闭单个会话到一个进程中的独立线程。

  • 使用复制过程中处理的会话,从而使派生进程句柄会议和原追溯到等待更多的连接。

  • use select to basically wait on a group of file descriptors until one of them is ready for reading or writing.
  • use threading, such as pthreads, to hand off individual sessions to separate threads within the one process.
  • use fork to replicate the process for handling a session, so that the forked process handles that session and the original goes back to waiting for more connections.

这些,我preFER中间的一个。分叉的过程中,该数据有时是昂贵的操作通常有如果进程试图去改变它被复制。

Of these, I prefer the middle one. Forking a process is a sometimes-expensive operation in that the data normally has to be copied if either process attempts to change it.

选项意味着你code具有管理多个会话,有时会导致混乱。

The select option means that your code has to manage multiple sessions and that can sometimes get messy.

使用线程,可以彼此分离相对容易的会话,而不会产生重复过程的成本。当然,线程都有自己的缺陷,如果你不小心,但我认为这是一个preferable选项一旦你理解了潜在的问题。

With threading, you can separate relatively easily the sessions from each other, without incurring the cost of process duplication. Of course, threading has its own pitfalls if you're not careful but I consider it a preferable option once you understand the potential problem areas.

这篇关于TCP服务器用C听多张客户一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆