tags:

views:

133

answers:

1

I read 2 C# chat source code & I see a problem: One source uses Socket class:

private void StartToListen(object sender , DoWorkEventArgs e)
{
    this.listenerSocket = new Socket(AddressFamily.InterNetwork , SocketType.Stream , ProtocolType.Tcp);
    this.listenerSocket.Bind(new IPEndPoint(this.serverIP , this.serverPort));
    this.listenerSocket.Listen(200);
    while ( true )
        this.CreateNewClientManager(this.listenerSocket.Accept());
}

And other one uses TcpListener class:

    server = new TcpListener(portNumber);
    logger.Info("Server starts");
    while (true)
    {
        server.Start();
        if (server.Pending())
        {
            TcpClient connection = server.AcceptTcpClient();
            logger.Info("Connection made");
            BackForth BF = new BackForth(connection);
        }
    }

Please help me to choose the one. I should use Socket class or TcpListener class. Socket connection is TCP or UDP? Thanks.

+3  A: 

UDP is connectionless, but can have a fake connection enforced at both ends on the socket objects. TCP is a stream protocol (what you send will be received in chunks on the other end), and additionally creates endpoint sockets for each accepted socket connection (the main listening socket is left untouched, although you'd probably need to call listen() again). UDP uses datagrams, chunks of data which are received whole on the other side (unless the size is bigger than the MTU, but that's a different story).

It looks to me like these two pieces of code are both using TCP, and so as the underlying protocol is the same, they should be completely compatible with each other. It looks as if you should use the second bit of code since it's higher level, but only the server can really use this, the client needs a different bit of code since it doesn't listen, it connects... If you can find the 'connecting' code at the same level of abstraction, use that.

Chris Dennett