异步Tcp socket遇到无法访问已释放的对象 System.Net.Sockets
客户端有个启动访问服务端的按钮,点击第一次是没有问题,但是点击第二次就遇到了问题,报
异常:遇到无法访问已释放的对象 System.Net.Sockets。现在怀疑是服务端的异步发送
引起的,handler.Shutdown(SocketShutdown.Both);handler.Close();客户端没有接收到传来的数据,为null,汇报异常,客户端报异常的代码我已经加红,请各位帮我看看咋回事,我不知道咋改了。
服务端:
Thread newThread;
public static ManualResetEvent allDone = new ManualResetEvent(false);
public delegate void SetRichTextBoxReceiveCallback(string str);
public SetRichTextBoxReceiveCallback setRichTextBoxReceiveCallback;
private void SetRichTextBoxReceive(string str)
{
if (rtb_Content.InvokeRequired)
{
setRichTextBoxReceiveCallback = new SetRichTextBoxReceiveCallback(SetRichTextBoxReceive);
rtb_Content.Invoke(setRichTextBoxReceiveCallback, str);
}
else
{
rtb_Content.AppendText(str);
}
}
private void btn_Start_Click(object sender, EventArgs e)
{
setRichTextBoxReceiveCallback = new SetRichTextBoxReceiveCallback(SetRichTextBoxReceive);
ThreadStart ts = new ThreadStart(acceptConnect);
newThread = new Thread(ts);
newThread.Start();
}
private void btn_Click(object sender, EventArgs e)
{
//newThread.Abort();
System.Environment.Exit(0);
}
/// <summary>
/// 开启一个socket监听线程
/// </summary>
private void acceptConnect()
{
IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8090);
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// 绑定端口,并监听发起的连接请求。
try
{
listener.Bind(endPoint);
listener.Listen(100);
while (true)
{
// Set the event to nonsignaled state.
allDone.Reset();
// Start an asynchronous socket to listen for connections.
SetRichTextBoxReceive("等待客户端连接请求中......\n");
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
// Wait until a connection is made before continuing.
allDone.WaitOne();
}
}
catch (Exception ex)
{
SetRichTextBoxReceive(ex.Message.ToString());
}
}
/// <summary>
/// 接收连接请求
/// </summary>
/// <param name="ar"></param>
public void AcceptCallback(IAsyncResult ar)
{
// Signal the main thread to continue.
allDone.Set();
// Get the socket that handles the client request.
// 获取处理客户端请求的套接字
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
// Create the state object.实例化类StateObject。
StateObject state = new StateObject();
state.workSocket = handler;
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
}
/// <summary>
/// 读取连接请求
/// </summary>
/// <param name="ar"></param>
private void ReadCallback(IAsyncResult ar)
{
string content = string.Empty;
// Retrieve the state object and the handler socket from the asynchronous state object.
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
// Read data from the client socket.
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
// There might be more data, so store the data received so far.
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
// Check for end-of-file tag. If it is not there, read more data.
content = state.sb.ToString();
if (content.IndexOf("<EOF>") > -1)
{
// All the data has been read from the client. Display it on the console.
SetRichTextBoxReceive("Read " + content.Length + " bytes from socket.\nData:" + content + ".\n");
// Echo the data back to the client.
Send(handler, content);
}
else
{
// Not all data received. Get more.
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
}
}
}
private void Send(Socket handler, String data)
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data);
// Begin sending the data to the remote device.
handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);
}
public void SendCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket handler = (Socket)ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = handler.EndSend(ar);
rtb_Content.Invoke(setRichTextBoxReceiveCallback, "Sent " + bytesSent + " bytes to client.\n");
handler.Shutdown(SocketShutdown.Both);
handler.Close(); }
catch (Exception ex)
{
throw ex;
}
}