C#关于侦听本地端口:关闭被侦听的端口后界面卡
由于项目的特殊需要创建了两个TCP通道,一个用于连接服务器发送数据,一个用于侦听本机端口接收数据,在接收完数据后关闭本机被侦听的端口,窗体突然间很卡 ,需要很长时间才可以响应下一个窗体,请问该怎么解决?代码如下侦听本地端口 接收数据:
delegate void aa();
TcpListener TcpListener = null;
TcpClient TcpClient = null;
NetworkStream MyStream = null;
/// <summary>
/// 监听9806端口
/// </summary>
private void StartListen()
{
this.TcpListener = new TcpListener(9806);
this.TcpListener.Start();
TcpClient = this.TcpListener.AcceptTcpClient();
MyStream = TcpClient.GetStream();
while (true)
{
try
{
byte[] bytes = new byte[2048];
int bytesRead = MyStream.Read(bytes, 0, bytes.Length);
string msg = System.Text.Encoding.UTF8.GetString(bytes, 0, bytesRead);
string[] su1 = msg.Split(new char[] { '/' });
if (msg != "")
{
aa a = delegate()
{
Dictionary<int, string> dic = new Dictionary<int, string>();
int i = 1;
foreach (string s in su1)
{
dic.Add(i, s.ToString());
i = i + 1;
}
}
}
}catch (Exception ex) {}
}
关闭被侦听的端口
private void button1_Click_1(object sender, EventArgs e)
{
MyStream.Close();
client.Close();
TcpClient.Close();
this.TcpListener.Stop();
} --------------------编程问答-------------------- 额,可以先用tcpListener.Server.Shutdown(SocketShutdown.Both);这个方法禁止数据的收发。再关闭Socket。。
补充:.NET技术 , C#