user1108948
user1108948

Reputation:

Set up a socket server

I need a class that will start a socket server and wait for connections. Here is my code:

 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);
        }
    }

However from the MSDN., we found that the code doesn't have TcpClient etc, which code is correct? Did I misunderstand the concept?

Upvotes: 0

Views: 87

Answers (1)

Viktor Arsanov
Viktor Arsanov

Reputation: 1583

I think, both are correct. I think, TcpListener/client is just a kind of a wrapper, it uses Socket inside it.

Just looked though decompiled code of 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);
}

and so on.

TcpListener, I think, provides some comfortable methods for you, Socket is more low-level.

Upvotes: 1

Related Questions