![]() |
Getting data from a socket when it arrives
I am currently in the process of writing a client that will connect to Battle.net and I was wondering if there was a way to catch data right when it arrives at the socket. The only way I can think of off the top of my head is to do something like this:
:
Dim BnetSock As SocketBut as you might imagine, that's really CPU intensive. :P If anyone has any ideas on how I might be able to instantaneously retrieve incoming data (I'm really hoping there is some kind of event that gets raised) please offer some assistance. |
It depends on the protocol. There is typically a field for the number of bytes to follow in the next chunk rather than an ending sentinel. In that case, I would use the more common overload of Receive (the one that takes a start position in the buffer, the bytes to read, etc) to make sure you get all the header bytes, allocate a new array of the specified size, and again use the more common overload of Receive to get all the bytes.
Here's an excerpt from the Element source code (Net.cs, BaseTcpConnection.ReceiveMessage). It uses TcpClient instead of Socket, but you get the idea. :
byte[] recvBuff = new byte[4];As for being cpu intensive, add a delay between each poll. If the code to read the socket is in its own thread, use Sleep for perhaps 0 or 1 milliseconds (0 yields to waiting threads without specifically setting an interval to wait). If not, you can get away with a timer. |
This thread/forum might be useful to you now and during your bots development. Check it out, follow the links.
http://forum.valhallalegends.com/index.php?topic=7220.0 |
The main issue I am having is that I don't know when to expect the data. It's a chat client, somewhat similar to IRC (you enter a room and there may be as many as 40 users typing at once) which is why I need to get all the data from the socket as it arrives.
Is the best thing to do still just add a wait for each poll? That is a waste of a lot of CPU cycles. EDIT: It's not a bot, it's going to be a plugin for Trillian. :) |
You could also use the non-blocking call Socket.BeginReceive which takes a pointer to a buffer and invokes a callback on a spawned temporary thread. However be sure to make use of the provided space for a state object for example if more data arrives while the callback is still running - it's there for a reason but you'll need to implement its workings yourself.
In fact here's a wrapper I had kicking around which is somewhat reminiscent of the old Winsock control. :) It's from a heavily multithreaded FTP server so multiple instances may not be happy together. Also the buffer size is a bit random too. :
Imports System |
| All times are GMT -5. The time now is 8:56 AM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC