c# - 如何修复错误 "Only one usage of each socket address (protocol/network address/port) is normally permitted"?

标签 c# exception networking tcplistener

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

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

我试过禁用防火墙、更改要使用的端口、移动变量但无济于事(客户端工作正常,但显然找不到服务器,因为我无法启动它)。

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

我的代码:

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

在我的主要方法中:

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

非常感谢任何帮助!

最佳答案

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

关于c# - 如何修复错误 "Only one usage of each socket address (protocol/network address/port) is normally permitted"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14654998/

相关文章:

c# - 我如何在 C# 中做到这一点?

c# - 如何将 Filter 应用于 PagedCollectionView 但防止 CollectionChanged 事件在编辑时触发?

c# - FluentValidation 验证器和简单注入(inject)器,其中验证器作为数组注入(inject)

android - 测试 TypedArray recycle() 不会抛出 RuntimeException

amazon-web-services - 通过 CNAME 别名访问应用程序时,什么会导致应用程序过时?

networking - linux内核中UDP包的路径

c# - Visual Studio 注册表捕获实用程序已停止工作,在 Windows7 中编译 C# 项目时出错

php - 为 DateTime 准备 PHP 代码

java - JDBC Oracle 结果集空指针异常

java - 私钥解密对称 key ,但对称 key 联网时给出不同的结果?