My question is when you have a proxy server and you need to send/recv with client and send/recv wi开发者_JAVA技巧th 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
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:
- 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.
- 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'sselect
sample in man page and lots of info on internet.
One famous page dedicated to servers development is here.
receive from client send to server while(true) { if(recvfrom server is not zero) send to client if(recvfrom client is not zero) send to server }
I think this might work..
Use select()
to wait for data to be available from either side, then read it and pass it over.
精彩评论