我已经停留了一段时间了,当从客户端向服务器发送请求时,服务器响应从sql数据库中提取的数据并且客户端收到它,一切正常。问题是当客户端再次向服务器请求数据时,这会给我以下错误:对象引用未设置为对象实例。事实上,在向我的数据库添加数据时,服务器可以接收多个请求。根据我的尝试捕获,当我的SendCallback调用我的方法来开始接收数据时发生错误。
private static void BeginAccept()
{
listener.Listen(5);
Thread t = new Thread(() =>
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener));
t.Start();
}
private static void AcceptCallback(IAsyncResult ar)
{
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
handler.BeginReceive(recBuf, 0, bufsize, 0, new AsyncCallback(ReceiveCallback), handler);
Console.WriteLine("client connected" );
}
private static void ReceiveCallback(IAsyncResult ar)
{
try
{
Console.WriteLine("Waiting for data...");
string content = string.Empty;
string[] pieces = null;
string[] delimiters = { "|" };
/*StateObject state = (StateObject)ar.AsyncState; */// Calling the socket from AcceptCallback.
Socket handler = (Socket)ar.AsyncState;
sb.Clear();
int dataReceived = handler.EndReceive(ar);
if (dataReceived > 0)
{
sb.Append(Encoding.ASCII.GetString(recBuf, 0,dataReceived));
if (content.IndexOf("<!ReqDB>") > -1)
{
try
{
Console.WriteLine("Following data received: " + content);
pieces = null;
pieces = content.Split(delimiters, StringSplitOptions.None);
sb = null;
Console.WriteLine("ReqDB received!!");
Int64 ID = Int64.Parse(pieces[0]);
RetrieveDataFromDB(handler, ID);
//Some other irrelevant code....
RetrieveDataFromDB将数据从数据库中提取出来,转换它并调用Send(处理程序,数据);
private static void Send(Socket handler, string data)
{
byte[] byteData = Encoding.ASCII.GetBytes(data);
handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);
}
private static void SendCallback(IAsyncResult ar)
{
try
{
Socket handler = (Socket)ar.AsyncState;
byte[] buffer = new byte[1024];
int bytesSend = handler.EndSend(ar);
handler.BeginReceive(recBuf, 0, bufsize, 0, new AsyncCallback(ReceiveCallback), handler);
}
catch (Exception e)
{
Console.WriteLine("Line 197: "+e.ToString());
}
}
某处,可能当SendCallback执行handler.beginReceive并调用该方法时,会发生错误,我不知道错误在哪里,或者导致错误的原因。我认为它是处理程序,但我不明白为什么它会导致它。