错误“通常只允许使用每个套接字地址(协议/网络地址/端口)”

时间:2015-11-02 10:43:06

标签: c# sockets tcplistener

我使用socket / tcplistener在windows application中处理发送方和接收方。

我收到此错误

  

每个套接字地址只有一种用法(协议/网络地址/端口)   通常是允许的

错误发生在StartReciever方法

的catch块中

以下是我的代码。

// On button click
private void btnLoadFile_SendFile_Click(object sender, EventArgs e)
      {

       StartReciever();
       SendData(tcpIpAddress, port, filename);
      }


  private void StartReciever()
        {
            util.LoadSettings();

            string tcpIpAddress = util.svrSettings["IpAddress"];
            string port = util.svrSettings["Port"];
            string outDir = util.svrSettings["isOutput"];

            new Thread(
        () =>
        {
            if (!File.Exists(util.settingFile))
                Logger("Please setup the services first.");
            else
            {
                try
                {
                    IPAddress ipAddress = IPAddress.Parse(tcpIpAddress);
                    TcpListener tcpListener = new TcpListener(ipAddress, Convert.ToInt32(port));

                    tcpListener.Start();

                    Logger("\nWaiting for a client to connect...");

                    //blocks until a client connects
                    Socket socketForClient = tcpListener.AcceptSocket();

                    Logger("\nClient connected");

                    //Read data sent from client
                    NetworkStream networkStream = new NetworkStream(socketForClient);
                    int bytesReceived, totalReceived = 0;

                    string fileName = "testing.txt";

                    byte[] receivedData = new byte[10000];
                    do
                    {
                        bytesReceived = networkStream.Read
                            (receivedData, 0, receivedData.Length);
                        totalReceived += bytesReceived;
                        Logger("Progress of bytes recieved: " + totalReceived.ToString());
                        if (!File.Exists(fileName))
                        {
                            using (File.Create(fileName)) { };
                        }

                        using (var stream = new FileStream(fileName, FileMode.Append))
                        {
                            stream.Write(receivedData, 0, bytesReceived);
                        }

                    }
                    while (bytesReceived != 0);
                    Logger("Total bytes read: " + totalReceived.ToString());

                    socketForClient.Close();
                    Logger("Client disconnected...");

                    tcpListener.Stop();
                }
                catch (Exception ex)
                {
                    // Error : "Only one usage of each socket address (protocol/network address/port) is normally permitted"     
                    Logger("There is some error: " + ex.Message); 
                }
            }
        }).Start();
        }



 private static void SendData(string tcpIpAddress, string port, string filename)
        {
            new Thread(
      () =>
      {
          TcpClient tcpClient = new TcpClient(tcpIpAddress, Convert.ToInt32(port));
          //const int bufsize = 8192;
          const int bufsize = 10000;
          var buffer = new byte[bufsize];
          NetworkStream networkStream = tcpClient.GetStream();

          using (var readFile = File.OpenRead(filename))
          {
              int actuallyRead;
              while ((actuallyRead = readFile.Read(buffer, 0, bufsize)) > 0)
              {
                  networkStream.Write(buffer, 0, actuallyRead);
              }
          }
      }).Start();
        }

2 个答案:

答案 0 :(得分:0)

我的猜测是,第一次按键点击启动的接收器仍然在运行,所以当你尝试在同一个地址和端口上设置第二个TcpListener时,你会得到例外。

您应该添加一些代码,以防止您并行创建两个相同的侦听器。

答案 1 :(得分:0)

您在Click事件处理程序中调用StartReceiver方法,这就是它第二次尝试打开同一端口的原因。它只需要调用一次,将其移动到其他位置,例如在程序初始化代码中。