0
class Program
{
    static Socket m_sock;

    static void Main(string[] args)
    {
        Socket m_sock= new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        .
        .
        .
        m_sock.Connect(ipendLocalhost);
        SendRequest("command");
    }

    static void SendRequest(string sCommand)
    {
       .
       .
     **m_sock.Send(szCommand, iBytesToSend, SocketFlags.None);**
     }

When it comes to Send method I get NullReferenceException. In debug (I added m_sock to watch) I See that when program enters SendRequest method m_sock becomes null. I can't understand why is it happening and where the problem is. Please help.

4

3 回答 3

2

m_sock在 Main 内部以及在类级别定义,您不必在 Main 中再次定义它,只需初始化它,例如:

static void Main(string[] args)
    {
        m_sock= new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

注意Socket被删除。

目前,您的 Main 方法正在初始化一个 local m_sock,这就是您的类级别m_sock保持为空的原因,稍后当您在静态方法中访问它时,您会遇到异常。

于 2013-08-26T16:53:47.790 回答
2

因为你m_sock在 Main 中声明了另一个

Socket m_sock=new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

将其更改为

m_sock=new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
于 2013-08-26T16:54:16.337 回答
2

问题来自您在 Main 中的声明,Socket m_sock=在类级别隐藏了该字段。

static Socket m_sock;
static void Main(string[] args)
{
    Socket m_sock = new Socket // Create a new Socket in m_sock from the Main method only
    SendRequest("command");
}

static void SendRequest(string sCommand)
{
  m_sock.Send() // Uses the socket at the Class level, which is not initialized
}

将初始化更改为

static void Main(string[] args)
{
    m_sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    m_sock.Connect(ipendLocalhost);

    SendRequest("command");
}

或删除类级别声明并将其作为变量传递

static void Main(string[] args)
{
    Socket m_sock= new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    m_sock.Connect(ipendLocalhost);

    SendRequest(m_sock, "command");
}

static void SendRequest(Socket m_sock, string sCommand)
{
   m_sock.Send(szCommand, iBytesToSend, SocketFlags.None);
}
于 2013-08-26T16:57:15.033 回答