The code below works fine. As of now I just set the buffer length real big and all is good. However, I hate the impreciseness of that.
So my question in general is how do I know what length to set the buffer? In specific, my question is what causes the 'completed' event in the OnSocketConnect Completed method to fire? Does it fire at end of a packet or does happen at some end of data marker?
So my question in general is how do I know what length to set the buffer? In specific, my question is what causes the 'completed' event in the OnSocketConnect Completed method to fire? Does it fire at end of a packet or does happen at some end of data marker?
Code:
public SocketClient(Page pg, Int32 port, Int32 length)
{
this.PAGE = pg;
this.LENGTH = length;
this.Q = new Queue<byte[]>();
DnsEndPoint endPoint = new DnsEndPoint("111.222.333.444", port);
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
SocketAsyncEventArgs argz = new SocketAsyncEventArgs();
argz.UserToken = socket;
argz.RemoteEndPoint = endPoint;
argz.Completed += new EventHandler<SocketAsyncEventArgs>(OnSocketConnectCompleted);
socket.ConnectAsync(argz);
}
private void OnSocketConnectCompleted(object sender, SocketAsyncEventArgs e)
{
byte[] response = new byte[this.LENGTH];
e.SetBuffer(response, 0, response.Length);
e.Completed += new EventHandler<SocketAsyncEventArgs>(OnSocketReceive);
Socket socket = (Socket)e.UserToken;
socket.ReceiveAsync(e);
}
private void OnSocketReceive(object sender, SocketAsyncEventArgs e)
{
Q.Enqueue(e.Buffer);
//Prepare to receive more data
Socket socket = (Socket)e.UserToken;
byte[] response = new byte[this.LENGTH];
e.SetBuffer(response, 0, response.Length);
socket.ReceiveAsync(e);
}
Comment