Question

I have a TCP listener that should recieve some messages from a client but when I start this simple server I get an error like this on server.Start():

Only one usage of each socket address (protocol/network address/port) is normally permitted

this is the code that I'm using:

public class ServerThread
{
    private readonly int port = 8000;
    private readonly IPAddress ip = IPAddress.Parse("xxxx");

    /// <summary>
    /// constructor, create the server thread
    /// </summary>
    public ServerThread()
    {
        Thread serverThread = new Thread(new ThreadStart(serverThreadStart));

        serverThread.Start();

        Console.WriteLine("Server thread started!");
    }

    /// <summary>
    /// start the server
    /// </summary>
    private void serverThreadStart()
    {
        TcpListener server = null;

        try
        {
            server = new TcpListener(ip, port);
            server.Start();

            Byte[] bytes = new Byte[256];
            String data = null;

            while (true)
            {
                Console.WriteLine("Waiting for client connection...");

                TcpClient client = server.AcceptTcpClient();
                data = null;
                NetworkStream stream = client.GetStream();
                int i;

                while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                {
                    data = Encoding.ASCII.GetString(bytes, 0, i);
                    data = data.ToUpper();
                    Byte[] msg = Encoding.ASCII.GetBytes(data);
                    stream.Write(msg, 0, msg.Length);
                }

                // Shutdown and end connection
                client.Close();
            }
        }
        catch(SocketException e)
        {
          Debug.WriteLine("SocketException: {0}", e);
        }
        finally
        {
            // Stop listening for new clients.
            server.Stop();
        }
    }
}

and the main method simply does this:

static void Main(string[] args)
{
    new ServerThread();
}
Était-ce utile?

La solution

Some other program is already listing in TCP port 8000. Only one program can listen on a TCP port at a time. You can either change the TCP port that your listener is using or figure our which program is also listening on port 8000 and stop it.

You can find out which programs are listing on a port by running netstat -a -b -p tcp from a command prompt.

Autres conseils

There must be some other program is using same port, Use following command, you will require admin permissions.

    netstat -a -b 

you can also try TCPView utili.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top