TCP Sockets - InvalidOperationException

本文关键字:InvalidOperationException Sockets TCP | 更新日期: 2023-09-27 18:25:10

我是C#网络的新手,在制作基本的客户端-服务器时遇到了一些问题。服务器运行良好,但当服务器启动并且客户端尝试连接时,它会抛出错误"套接字不得绑定或连接"。一些额外的细节是,服务器和客户端在禁用exclusiveAddressUse的情况下运行在同一台计算机上。

客户代码:

this.client = new TcpClient(this.settings.GetByName("MasterServerIP").Value, int.Parse(this.settings.GetByName("MasterServerPort").Value)) { ExclusiveAddressUse = false };
this.client.Connect(IPAddress.Parse(this.settings.GetByName("MasterServerIP").Value), int.Parse(this.settings.GetByName("MasterServerPort").Value));
this.writer = new BinaryWriter(this.client.GetStream());
this.reader = new BinaryReader(this.client.GetStream());

服务器代码:

this.Listener.Start();
TcpClient tcpClient;
while (this.Listener.Server.Connected)
{
tcpClient = this.Listener.AcceptTcpClient();
System.Threading.Thread t = new System.Threading.Thread(() => { this.ProcessClient(tcpClient); }); //Runs the thing on another thread so this can be accepting another client
t.Start();
}

编辑:即使删除了connect方法调用,它仍然抛出相同的错误。有什么帮助吗?

TCP Sockets - InvalidOperationException

当您使用主机和端口创建TCPClient时,它会自动连接。然后您就不需要再次连接了。

请参阅http://msdn.microsoft.com/en-us/library/System.Net.Sockets.TcpClient(v=vs.110).aspx获取详细信息。

关于你的评论,当你删除连接调用时,它仍然失败,要么你仍然在运行其他代码,要么有其他问题。以下代码运行良好:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
namespace testtcp {
    class Program {
        static void Main(string[] args) {
            TcpClient client = new TcpClient("www.google.com", 80);
            //client.Connect("www.microsoft.com", 80);
        }
    }
}

但是,当您取消注释Connect调用时,您会得到一个SocketException,其中包含expanatory文本:

{"A connect request was made on an already connected socket"}

然而,这实际上是一个与您收到的错误消息不同的错误消息,导致我们相信上面的"还有其他问题"。

如果你在这里查看TcpClient.ExclusiveAddressUse的在线文档,你会注意到以下片段(我的粗体):

在将基础套接字绑定到客户端端口之前,必须设置此属性。如果调用ConnectBeginConnectTcpClient(IPEndPoint)TcpClient(String, Int32),,则客户端端口被绑定为该方法的副作用,并且随后不能设置ExclusiveAddressUse属性。

事实上,以下代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
namespace testtcp {
    class Program {
        static void Main(string[] args) {
            TcpClient client = new TcpClient("www.google.com", 80) {
                ExclusiveAddressUse = false
            };
        }
    }
}

为您提供所描述的精确异常。

因此,最重要的是,如果希望使用ExclusiveAddressUse,不要尝试将其与主机和端口构造函数一起使用,因为这将绑定套接字,并且尝试的属性更改将引发异常。相反,(作为一种可能性)使用无参数构造函数,更改属性,然后连接

问题出现在客户端代码的前两行:

this.client = new TcpClient(this.settings.GetByName("MasterServerIP").Value, int.Parse(this.settings.GetByName("MasterServerPort").Value)) { ExclusiveAddressUse = false };
this.client.Connect(IPAddress.Parse(this.settings.GetByName("MasterServerIP").Value), int.Parse(this.settings.GetByName("MasterServerPort").Value));

当您在第一行调用构造函数时,您已经在连接TcpClient,因此之后的Connect调用是无效的。移除它,它就会工作。

从文档中,构造函数:

初始化TcpClient类的新实例,并连接到指定主机上的指定端口。

相关文章:
  • 没有找到相关文章