C# 如何修复错误“通常每个套接字地址(协议/网络地址/端口)只允许使用一次”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14654998/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:35:56  来源:igfitidea点击:

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

c#exceptionnetworkingtcplistener

提问by Stephen Foster

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)

我已经做了很多谷歌搜索,但我的问题没有太多运气。我是网络编程的新手并试图学习,我试图建立一个简单的服务器和客户端进行通信(遵循位于此处的在线教程 - > http://tech.pro/tutorial/704/csharp-tutorial-简单线程tcp服务器

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.

我遇到的问题是,在尝试在服务器上启动 TcpListener 时,我不断收到异常“通常只允许使用每个套接字地址(协议/网络地址/端口)一次”。

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.

我看过描述使用 Socket.Poll() 的解决方案,但由于我只使用 TcpListener 对象,我不知道如何使用 Poll 函数。

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!

非常感谢任何帮助!

采纳答案by Ryan Cavanaugh

ListenForClientsis getting invoked twice (on two different threads) - once from the constructor, once from the explicit method call in Main. When two instances of the TcpListenertry to listen on the same port, you get that error.

ListenForClients被调用两次(在两个不同的线程上) - 一次来自构造函数,一次来自Main. 当两个实例TcpListener尝试侦听同一个端口时,您会收到该错误。

回答by mansoor

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.

您正在调试两次或更多次。所以应用程序可以一次运行更多。那么只会出现这个问题。您应该使用任务管理器关闭所有调试应用程序,然后再次调试。

回答by Amit Bhargava

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

我在 windows server 2012 STD 64 位上遇到了类似的问题,在使用所有可用的 windows 更新更新 windows 后,我的问题得到了解决。