visual studio socket net example ejemplo c# exception networking tcplistener

studio - tcplistener c# example



¿Cómo soluciono el error "Normalmente solo se permite el uso de cada dirección de socket(protocolo/dirección de red/puerto)"? (3)

Estás depurando dos o más veces. por lo que la aplicación puede ejecutarse más a la vez. Entonces solo este problema ocurrirá. Debe cerrar todas las aplicaciones de depuración usando task-manager, luego depurar de nuevo.

He hecho muchas búsquedas en Google pero no tuve mucha suerte con mis problemas. Soy nuevo en la programación de redes y trato de aprender, he intentado configurar un servidor simple y un cliente que se comunique (siguiendo un tutorial en línea ubicado aquí -> http://tech.pro/tutorial/704/csharp-tutorial-simple-threaded-tcp-server )

El problema que estoy teniendo es que sigo obteniendo la excepción "Normalmente solo se permite el uso de cada dirección de socket (protocolo / dirección de red / puerto) cuando intento iniciar el TcpListener en el servidor.

Intenté inhabilitar mi firewall, cambiar el puerto que se usaría, mover las variables pero no sirvió (el cliente funciona bien, pero obviamente no puede encontrar el servidor porque no puedo abrirlo).

He visto soluciones que describen el uso de Socket.Poll () pero como solo uso el objeto TcpListener, no tengo idea de cómo hacer uso de la función Encuesta.

Mi código:

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

En mi método principal:

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

¡Cualquier ayuda es muy apreciada!


Me enfrenté a un problema similar en Windows Server 2012 STD de 64 bits, mi problema se resuelve después de actualizar Windows con todas las actualizaciones de Windows disponibles.


ListenForClients se invoca dos veces (en dos subprocesos diferentes), una vez desde el constructor, una vez desde la llamada al método explícito en Main . Cuando dos instancias del TcpListener intentan escuchar en el mismo puerto, obtienes ese error.