[c#] How do I fix the error "Only one usage of each socket address (protocol/network address/port) is normally permitted"?

I've done a lot of googling but not had much luck with my issues. I am new to network programming and trying to learn, I've attempted to set up a simple server & client that communicate (following an online tutorial located here -> http://tech.pro/tutorial/704/csharp-tutorial-simple-threaded-tcp-server)

The issue I'm having is that I keep getting the exception "Only one usage of each socket address (protocol/network address/port) is normally permitted" when trying to start the TcpListener on the server.

I've tried disabling my firewall, changing the port to be used, moving variables around but to no avail (the client works fine, but it obviously can't find the server because I cannot launch it).

I've seen solutions describing the use of Socket.Poll() but since I'm only using the TcpListener object, I have no idea how to make use of the Poll function.

My code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.Text;

namespace ServerTutorial {
class Server {
    private readonly Thread m_listenThread;

    public Server() {
        m_listenThread = new Thread(new ThreadStart(ListenForClients));
        m_listenThread.Start();
    }

    public void ListenForClients() {
        var listener = new TcpListener(IPAddress.Any, 3000);
        listener.Start();

        while (true) {
            //Blocks until a client has connected to the server
            TcpClient client = listener.AcceptTcpClient();

            //Send a message to the client
            var encoder = new ASCIIEncoding();
            NetworkStream clientStream = client.GetStream();
            byte[] buffer = encoder.GetBytes("Hello Client!");
            clientStream.Write(buffer, 0, buffer.Length);
            clientStream.Flush();

            //Create a thread to handle communication with the connected client
            var clientThread = new Thread(new ParameterizedThreadStart(HandleClient));
            clientThread.Start(client);
        }
    }

    private void HandleClient(object clientObj) { //Param thread start can only accept object types, hence the cast
        var client = (TcpClient) clientObj;
        NetworkStream clientStream = client.GetStream();

        var message = new byte[4096];

        while (true) {
            int bytesRead = 0;

            try {
                //Block until a client sends a message
                bytesRead = clientStream.Read(message, 0, 4096);
            } catch {
                //A socket error has occurred
                System.Diagnostics.Debug.WriteLine("A socket error has occured");
                break;
            }

            if (bytesRead == 0) {
                //The client has disconnected from the server
                System.Diagnostics.Debug.WriteLine("A client has disconnected from the server");
                client.Close();
                break;
            }

            //Message has been received
            var encoder = new ASCIIEncoding();
            System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));
        }
    }
}
}

In my main method:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ServerTutorial {
class Program {
    static void Main(string[] args) {
        var server = new Server();
        server.ListenForClients();
    }
}
}

Any help is hugely appreciated!

This question is related to c# exception networking tcplistener

The answer is


I faced similar problem on windows server 2012 STD 64 bit , my problem is resolved after updating windows with all available windows updates.


You are debugging two or more times. so the application may run more at a time. Then only this issue will occur. You should close all debugging applications using task-manager, Then debug again.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to exception

Connection Java-MySql : Public Key Retrieval is not allowed How to print an exception in Python 3? ASP.NET Core Web API exception handling Catching FULL exception message How to get exception message in Python properly What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean? what does Error "Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)" mean? Argument Exception "Item with Same Key has already been added" The given key was not present in the dictionary. Which key? sql try/catch rollback/commit - preventing erroneous commit after rollback

Examples related to networking

Access HTTP response as string in Go Communication between multiple docker-compose projects Can't access 127.0.0.1 How do I delete virtual interface in Linux? ConnectivityManager getNetworkInfo(int) deprecated Bridged networking not working in Virtualbox under Windows 10 Difference between PACKETS and FRAMES How to communicate between Docker containers via "hostname" java.net.ConnectException: failed to connect to /192.168.253.3 (port 2468): connect failed: ECONNREFUSED (Connection refused) wget: unable to resolve host address `http'

Examples related to tcplistener

How do I fix the error "Only one usage of each socket address (protocol/network address/port) is normally permitted"? How many socket connections can a web server handle?