Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Getting Single lines from an async socket

Status
Not open for further replies.

plasmatwin

Programmer
Nov 1, 2005
31
GB
I'm writing an IRC client library in c# using the Aynchronous Socket model in .NET. I am currently at a problem where, when recieving data from the socket, the program simply fills its buffer (a byte[256]) with data from the socket and hands it to me. The problem is that this array could contain a single line (often does) or it could contain half a line (since the line is longer than 256 chars) or it could contain 2 lines (if two lines arrived in the socket in the time it took me to perform the read after recieving the last lot) it could also contain one and a half lines. Therefor I need some code that inspects the array and sepperates it into it's sepperate lines. I have a string builder in my state object for the purpose of storing peices of a line that is split across two reads, but I have no idea on how to do the inspection of the array... here is my state object:
Code:
class StateObject
{
	// Size of receive buffer.
	public const int BufferSize = 512;
	// Receive buffer.
	public byte[] buffer = new byte[BufferSize];
	// Received data string.
	public StringBuilder sb = new StringBuilder();
}

ideas?
 
This is basic socket programming.

The key thing to realize is that sockets are a stream-based protocol (it's all just a series of bytes) and not a message-oriented protocol (it's a series of records or lines)

So I would suggest that you pass your array of bytes up to a higher level that is able to interpret the bytes and decide if a complete line has been received.

Yes: remove that part from your buffer and go off and process it (or raise an event and let someone else process it)

No: Append it to your buffer and make another request.

Since you're writing an IRC client, and such clients routinely come under attack, I would also suggest you add a "MaxLineLength" value (say, 2000 characters) to prevent someone from sending you 1,000,000 characters all on one line.

Chip H.


____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top