Socket线程不能正常退出,各位大侠帮帮忙,在线等

afeicn 2005-12-18 10:26:48
我做了一个网络通信的小程序,服务器端的Socket在没有完成线程工作时退出总是不能完全释放资源,就是说任务管理器中还有这个进程,总是导致下次无法运行,各位大哥帮帮忙,很急,谢谢了!

这是线程的代码:
static String content = String.Empty;
public static string data = null;

// Thread signal.
public static ManualResetEvent allDone = new ManualResetEvent(false);

public static ThreadStart aTh=new ThreadStart(Form1.Listening);
public static Thread myThread=null;
public static byte[] bytes = new Byte[1024];
public static Socket handler=null;
public static Form1 f1=new Form1();
public static IPAddress addr =null;
public static IPEndPoint localEndPoint = null;


// Create a TCP/IP socket.
public static Socket listener=null;

static StateObject state;

public static void Listening()
{
int p=18120;
if(f1.textBox1.Text!="")
{
try
{
p=int.Parse(f1.textBox1.Text);
}
catch(Exception ex)
{
f1.richTextBox2.AppendText("\n"+ex.Message);
}
}

addr =new IPAddress(Dns.GetHostByName(Dns.GetHostName()).AddressList[0].Address);
localEndPoint = new IPEndPoint(addr,p);

// Create a TCP/IP socket.
Socket listener = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp );

// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.

// Bind the socket to the local endpoint and
// listen for incoming connections.
listener.Bind(localEndPoint);
while(true)
{
listener.Listen(10);
try
{
f1.richTextBox2.Text="******************************";
f1.richTextBox2.AppendText("\nTCP Socket Server started!");
f1.richTextBox2.AppendText("\nIP Address is: "+addr.ToString());
f1.richTextBox2.AppendText("\nListening Port is: "+p.ToString());
f1.richTextBox2.AppendText("\n******************************");
f1.richTextBox2.AppendText("\nwaiting for a connection...\n");


// Start listening for connections.

// Program is suspended while waiting for an incoming connection.
data = null;

// An incoming connection needs to be processed.

while (true)
{
allDone.Reset();

listener.BeginAccept(new AsyncCallback(AcceptCallback),listener);

allDone.WaitOne();
}

}
catch (Exception ex)
{
f1.richTextBox2.AppendText(ex.Message);
}

}
}


回调函数
public static void AcceptCallback(IAsyncResult ar)
{
// Signal the main thread to continue.
allDone.Set();

// Get the socket that handles the client request.
listener = (Socket) ar.AsyncState;
handler = listener.EndAccept(ar);

// Create the state object.
state = new StateObject();
state.workSocket = handler;
handler.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0,new AsyncCallback(ReadCallback), state);

}

public static void ReadCallback(IAsyncResult ar)
{

// Retrieve the state object and the handler socket
// from the asynchronous state object.
state = (StateObject) ar.AsyncState;
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.
if(content.EndsWith("<EOF>0"))
content=des.Decode(content.TrimEnd("<EOF>0".ToCharArray()),"12345678");
else
content=content.TrimEnd("<EOF>".ToCharArray());
f1.richTextBox2.AppendText( "\nConnect to "+IPAddress.Parse(((IPEndPoint)handler.RemoteEndPoint).Address.ToString())+":18120 Successfully!\n");
f1.richTextBox2.AppendText( "Text received Successfully!\n"+"Read "+content.Length.ToString()+" bytes from socket. \n");
f1.richTextBox1.Text=content;
// Echo the key to the client.
Send(handler,"Success!");

}
else
{
// Not all data received. Get more.
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,new AsyncCallback(ReadCallback), state);
}
}
}

private static 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);
}

private static 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);
f1.richTextBox2.AppendText("\nAlready sent" +bytesSent.ToString()+" bytes to client.");
f1.richTextBox2.AppendText("\nWaiting for a connection...\n");
handler.Shutdown(SocketShutdown.Both);
handler.Close();

}
catch (Exception e)
{
f1.richTextBox2.AppendText(e.ToString());
}
}



private void button2_Click(object sender, System.EventArgs e)
{
this.Close();
}

}
public class StateObject
{
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 1024;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
}
...全文
145 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
bbdog 2005-12-20
  • 打赏
  • 举报
回复
最简单的办法在你的窗口的Close事件里面添加
System.Environment.Exit(0);
强制关闭窗口

lxf31 2005-12-20
  • 打赏
  • 举报
回复
再顶

请哪位大侠给回答一下
lxf31 2005-12-20
  • 打赏
  • 举报
回复
再顶
lxf31 2005-12-20
  • 打赏
  • 举报
回复
这个问题有人回答么?

我也遇到了这个问题!!


超越大大 2005-12-20
  • 打赏
  • 举报
回复
退出程序前,先关闭socket

110,535

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧