如何知道何时从客户端服务器C ++发送/接收字节 [英] How to know when bytes are to send/recv from client server c++

查看:79
本文介绍了如何知道何时从客户端服务器C ++发送/接收字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是,当您有代理服务器并且需要与客户端发送/接收和与远程服务器发送/接收时,您如何知道在哪端有数据要发送/接收,所以我可以调用适当的功能. 我需要从网站向客户端(通过代理)和从客户端向服务器(通过代理)接收/发送字节,但是我不知道它们以什么顺序出现,我发现对于大多数站点来说这是不同的. br> 我当前的实现是这样:

My question is when you have a proxy server and you need to send/recv with client and send/recv with remote server how do you know at what end there is data to be send/recv so I can call the appropriate functions. I need to recv/send bytes from a website to a client(via proxy) and from client to server (via proxy), but I don't know in what order they are coming,I saw that is different for most sites.
My current implementation is this:

1) receive from client
2) send to server
//infinite loop here
3) receive from server
4) send to client
// until bytes from server is 0

这仅适用于一些站点,并且无法完全加载它们,只有15-20 KB.
有什么建议吗?

This just works for a few sites,and doesn't load them completely, only 15-20 KB.
Any suggestions?

推荐答案

您的任务是将数据从客户端转发到服务器,然后再转发回来.由于客户端和服务器可以同时传输数据,因此从客户端读取所有内容(而不是将其传递给服务器,反之亦然)的方法将不起作用:请考虑等待客户端开始传输的情况,并且客户端要在启动客户端之前从服务器获取数据自己传输.
因此,有以下几种方法可以使其起作用:

Your task will be forwarding data from client to server and back. Since client and server can transmit data simultaneously, approach when you read everything from client than pass it to server and vice versa won't work: consider situation when you waiting for client to start transmission, and client wants to data from server before starting its own transmission.
So, there are following ways to make it work:

  1. 构建两个显式管道-一个从客户端到服务器的管道,另一个从服务器到客户端的管道.这将需要4个线程-一个从客户端读取并将数据传递给其他写入服务器的线程,反之亦然.这样做的缺点是每个客户端有4个线程,这限制了代理可以支持的并发客户端数量.
  2. 使用select(2)功能(或Windows API中类似的sys调用)+非阻塞套接字.这将告诉您何时有数据要读取或写入.如果要为每个线程提供多个客户端,则需要非阻塞套接字,因此在读/写syscall中线程不会被阻塞.
    手册页中有select示例,互联网上有很多信息.
  1. Build two explicit pipes -- one from client to server, another from server to client. This will require 4 threads -- one reading from client and passing data to other writing to server, and vice versa. This have drawback of having 4 threads per client which limits number of simultaneous clients your proxy can support.
  2. Employ select(2) functionality (or similar sys call from Windows API) + nonblocking sockets. This will tell you when there's data to be read or written. Non-blocking sockets are needed if you want to serve several clients per one thread, so thread won't become blocked in read/write syscall.
    There's select sample in man page and lots of info on internet.

此处是一个致力于服务器开发的著名页面.

One famous page dedicated to servers development is here.

这篇关于如何知道何时从客户端服务器C ++发送/接收字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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