【问题标题】:TcpListener will not startTcpListener 不会启动
【发布时间】:2014-03-23 20:41:31
【问题描述】:

我有一个 TCP 侦听器,它应该从客户端接收一些消息,但是当我启动这个简单的服务器时,我在 server.Start() 上收到类似这样的错误:

每个套接字地址(协议/网络地址/端口)通常只允许使用一次

这是我正在使用的代码:

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

main 方法就是这样做的:

static void Main(string[] args)
{
    new ServerThread();
}

【问题讨论】:

  • 显示输出消息“服务器线程已启动”?您可以尝试在其他函数中初始化侦听器,而不是在构造函数中。

标签: c# tcplistener


【解决方案1】:

其他程序已经在 TCP 端口 8000 中列出。一次只有一个程序可以侦听 TCP 端口。您可以更改您的侦听器正在使用的 TCP 端口,也可以确定我们的哪个程序也在侦听端口 8000 并停止它。

您可以通过在命令提示符下运行netstat -a -b -p tcp 来找出端口上列出了哪些程序。

【讨论】:

    【解决方案2】:

    必须有其他程序使用相同的端口,使用以下命令,您将需要管理员权限。

        netstat -a -b 
    

    你也可以试试TCPViewutili。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-14
      相关资源
      最近更新 更多