i receiving large numbers of messages , make receivedcallback more efficient.
i using convenient string handling - there faster way?
public class stateobject { public socket socket = null; public const int buffersize = 256; public byte[] buffer = new byte[buffersize]; public stringbuilder sb = new stringbuilder(); public string sessionid() { return socket.handle.tostring(); } } public void receivedcallback(iasyncresult ar) { stateobject state = (stateobject)ar.asyncstate; socket socket = state.socket; try { int bytesread = socket.endreceive(ar); if (bytesread > 0) { state.sb.append(encoding.ascii.getstring(state.buffer, 0, bytesread)); string[] contents = state.sb.tostring().split('@'); int delimcount = state.sb.tostring().count(x => x == '@'); (int d = 0; d < delimcount; d++) { if (contents[d] != "") onmessage(state, contents[d]); } if (!state.sb.tostring().endswith("@")) { state.sb.clear(); state.sb.append(contents[contents.count() - 1]); } else { state.sb.clear(); } socket.beginreceive(state.buffer, 0, state.buffer.length, socketflags.none, new asynccallback(receivedcallback), state); } else { // if no data recieved connection dead outputwriteline("client " + state.sessionid() + " disconnected"); socket.shutdown(socketshutdown.both); socket.close(); } } catch (exception ex) { messagebox.show(ex.message, "unusual error during receive!"); } }
there fundamental problem here: leaving socket w/o buffer while you're processing current one. kernel might drop packets, leading retries. high throughput should post multiple buffers , re-post new, empty buffers receive completes, before processing completed one. that being said, achieving correct processing multiple buffers very hard, must keep track of order posted , must handle incomplete messages (you cannot repost partially filled buffer 'rest' of message because there buffer posted). read articles linked @ high performance windows programs more details.
now, code have: profile it. start beginners guide performance profiling. suspect you'll find usual culprits (eg. allocations in string.split()) suggest measure yourself, find bottlenecks , make changes.
for string processing, read classic: why gnu grep fast (altough searching single @ not going impactful using boyer-moore). if possible, consider changing protocol more parsing friendly (eg. binary proto buff).
Comments
Post a Comment