设置套接字服务器

时间:2014-06-11 15:03:31

标签: c# .net sockets

我需要一个启动套接字服务器并等待连接的类。这是我的代码:

 public static void StatServer()
    {
        TcpClient client;
        TcpListener tcpListener;
        int _serverport = 9898;
        tcpListener = new TcpListener(System.Net.IPAddress.Any, _serverport);
        try
        {
            tcpListener.Start();
            while (true)
            {
                if (tcpListener.Pending())
                {
                    client = tcpListener.AcceptTcpClient();
                    Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
                    clientThread.Start(client);
                }
            }
        }
        catch (SocketException ex)
        {
            Console.WriteLine(ex.Message);
        }
    }

但是从MSDN.,我们发现代码没有TcpClient等,哪些代码是正确的? 我误解了这个概念吗?

1 个答案:

答案 0 :(得分:1)

我认为,两者都是正确的。我认为,TcpListener / client只是一种包装器,它在里面使用Socket。

看看TcpListener的反编译代码

private Socket m_ServerSocket;

...

public TcpListener(IPEndPoint localEP)
{
  if (Logging.On)
    Logging.Enter(Logging.Sockets, (object) this, "TcpListener", (object) localEP);
  if (localEP == null)
    throw new ArgumentNullException("localEP");
  this.m_ServerSocketEP = localEP;
  this.m_ServerSocket = new Socket(this.m_ServerSocketEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  if (!Logging.On)
    return;
  Logging.Exit(Logging.Sockets, (object) this, "TcpListener", (string) null);
}

等等。

我认为,TcpListener为您提供了一些舒适的方法,Socket更低级。