Socket端口监听无法关闭,那位高人给指点1and2

gjw 2007-04-27 01:25:21
public Socket mySocket;
public TcpListener listener;
public NetworkStream netStream;
public IPEndPoint IPE;
public Thread thread;
public byte[] ReveiceData = new byte[200];
public bool Control = true;

public void StartListening()
{
try
{
int Port = 4000;
IPAddress IP = IPAddress.Parse("192.168.1.27");
IPE = new IPEndPoint(IP, Port);
listener = new TcpListener(IPE);
listener.Start();
this.Text = "监听状态: 开启.";
Thread ListenThread = new Thread(new ThreadStart(clientConnect));
ListenThread.Start();
}
catch (Exception ListenError)
{ MessageBox.Show(ListenError.Message); }
}

public void clientConnect()
{
while (Control)
{
mySocket = listener.AcceptSocket();
if (mySocket.Connected)
{
this.Text = " 连接状态: 客户端建立连接.";
Thread thread = new Thread(new ThreadStart(Round));
thread.Start();
}
else this.Text = " 连接状态: 客户端断开连接.";
}
}

public void Round()
{
while (true)
{
netStream = new NetworkStream(mySocket);
netStream.Read(ReveiceData, 0, ReveiceData.Length);
this.BeginInvoke(new ShowDelegate(DataShow));
}
}

public delegate void ShowDelegate();
public void DataShow()
{
this.Text = "OK";
}

public void StopListen()
{
try
{
Control = false;
mySocket.Close();
listener.Stop();
this.Text = "监听状态: 关闭.";
}
catch (Exception StopError)
{ MessageBox.Show(StopError.Message); }
}

private void button1_Click(object sender, EventArgs e)
{
StopListen();
}

private void button2_Click(object sender, EventArgs e)
{
StartListening();
}

错误提示:未将对象引用设置到对象的实例,不明白???
...全文
610 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
gjw 2007-04-27
  • 打赏
  • 举报
回复
if (mySocket != null) mySocket.Close; 试过咧,还是listener.Stop();会报错,提示 : 一个封锁操作被对 WSACancelBlockingCall 的调用中断。
fangbuge 2007-04-27
  • 打赏
  • 举报
回复
if (mySocket != null) mySocket.Close;
gjw 2007-04-27
  • 打赏
  • 举报
回复
如果把这行去掉,listener.Stop();就会报错,提示 一个封锁操作被对 WSACancelBlockingCall 的调用中断。再没有地方放这一句啊!
wzd24 2007-04-27
  • 打赏
  • 举报
回复
我看了你的代码,把这行去掉!它不应该放在这里的。
如果没有客户端接入的话,一定会出这个异常的!
gjw 2007-04-27
  • 打赏
  • 举报
回复
是mySocket.Close();出错
wzd24 2007-04-27
  • 打赏
  • 举报
回复
是哪一行出错??

110,534

社区成员

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

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

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