【问题标题】:creating TCPClient giving me exception创建 TCPClient 给我例外
【发布时间】:2013-04-09 21:52:37
【问题描述】:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
        IPEndPoint ip = new IPEndPoint(Dns.GetHostAddresses("localhost")[0],8080);
        List<TcpClient> TCPs = new List<TcpClient>();
        int i = 1;
            while (true) {
                Console.Write(i + " ");
                /* the exception's row */ TCPs.Add(new TcpClient(ip));
                i++;
            }
        }
    }
}

给我这个例外:

 An attempt was made to access a socket in a way forbidden by its access permissions.

【问题讨论】:

标签: c# sockets exception tcpclient


【解决方案1】:

您不能多次绑定到同一个端口。由于您的while(true) 循环,您一遍又一遍地创建一个新的TcpClient。您创建的第一个将抢占端口 8080,而第二个因此异常而失败。

来自docs

在调用此构造函数之前,您必须使用要从中发送和接收数据的 IP 地址和端口号创建一个 IPEndPoint。

创建客户端时通常不需要设置端口。

【讨论】:

  • 嘿?我需要做什么?
  • 我不知道。你想达到什么目标?你的代码试图创造不可能的东西。
猜你喜欢
  • 2023-03-21
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-15
  • 1970-01-01
  • 2015-09-05
  • 1970-01-01
相关资源
最近更新 更多