如何关闭插座??? [英] How close socket ???

查看:138
本文介绍了如何关闭插座???的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


有问题:
我以关闭事件的形式编写此代码

hi ,
there is problem :
im writing this code in form close event

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    client.Shutdown(SocketShutdown.Both);//error :Object reference not sent to an instance of an object 
    client.Close();
}



当两个程序(发送和接收程序)都连接时,没有问题
但是当我打开服务器程序并关闭它,然后再将其连接到客户端程序时,显示此错误,我最想删除它的是什么?
好的客户端程序:



when both programs (send and recieve program )are connected , there is no problem
but when i open server program and , close it before connect it to client program , this error shown , what i most to do to remove it ?
ok client program :

private void Form1_Load(object sender, EventArgs e)
{
    IPAddress host = IPAddress.Parse("192.168.0.100");
    hostep = new IPEndPoint(host, 8001);
    sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    try
    {
        sock.Connect(hostep);
        timer1.Enabled = true;
    }
    catch (Exception a)
    {
        label1.Text = a.Message;
    }
}


这是从服务器接受套接字的块.


this is block that accept socket from server .

推荐答案

除非未显示代码中的相关错误,否则您可以像下面这样轻松解决它:

Unless there are related errors in code not shown, you could easily solve it like this:

private void Form1_FormClosing(object sender, FormClosingEventArgs e) {
    if (client!=null) {
        client.Shutdown(SocketShutdown.Both);// no NullRefExc
        client.Close();
    }
}



:)



:)


由于错误是对象引用未设置为对象的实例",因此最有可能的罪魁祸首是"client"为null.由于我们看不到将其加载到何处,因此我会进行检查.
Since the error is "Object reference not set to an instance of an object" the most likely culprit is that "client" is null. Since we can''t see where you load this, I would check that.


您在Load处理程序中使用的是名为sock的变量,但其中一个名为client的变量在您的FormClosing处理程序中.这两个代码段是否来自同一程序?

如果未将client设置为Socket实例,则它将为null并导致您看到的异常.

尼克
You are using a variable called sock in your Load handler, but one called client in your FormClosing handler. Are these two code snippets from the same program?

If you don''t set client to a Socket instance, then it will be null and cause the exception you are seeing.

Nick


这篇关于如何关闭插座???的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆