【问题标题】:TCPClient Error: "System.InvalidOperationExceptio"TCPClient 错误:“System.InvalidOperationException”
【发布时间】:2017-06-18 15:29:24
【问题描述】:

我一直在创建一个 TCPClient,它应该连接到服务器,但出现此错误:

System.InvalidOperationException: '该操作不允许 未连接的套接字。'

这是我的代码:

Public String IPAddress = "192.168.100.xxx"
Public Int32 Port = 23;
public TcpClient client = new TcpClient();

public void Connect() {
    client.Connect(IPAddress, Port);
    // send first message request to server
    Byte[] msg_data = System.Text.Encoding.ASCII.GetBytes("Hello Server);

    // uses the GetStream public method to return the NetworkStream
    NetworkStream netStream = _client.GetStream();

    // write message to the network
    netStream.Write(msg_data, 0, msg_data.Length);

    // buffer to store the response bytes
    msg_data = new Byte[256];

    // read the first batch of response byte from arduino server
    Int32 bytes = netStream.Read(msg_data, 0, msg_data.Length);
    received_msg = System.Text.Encoding.ASCII.GetString(msg_data, 0, bytes);

    netStream.Close();

}

public void Send() {
    // message data byes to be sent to server
    Byte[] msg_data = System.Text.Encoding.ASCII.GetBytes(_sendMessage);

    // uses the GetStream public method to return the NetworkStream

    // ** Error Here: System.InvalidOperationException: 'The operation is not allowed on non-connected sockets.'
    NetworkStream netStream = client.GetStream(); 

    // write message to the network
    netStream.Write(msg_data, 0, msg_data.Length);

    // buffer to store the response bytes
    msg_data = new Byte[256];

    // read the first batch of response byte from arduino server
    Int32 bytes = netStream.Read(msg_data, 0, msg_data.Length);
    received_msg = System.Text.Encoding.ASCII.GetString(msg_data, 0, bytes);

    netStream.Close(); // close Stream
}

创建NetworkStream netStream = client.GetStream(); 的新实例时出现错误。一直在努力寻找导致错误的原因,我认为它以某种方式关闭了上面的连接。

一切都在一个类中,必须在软件的任何地方调用。

【问题讨论】:

  • 连接时好像关闭了网络流——这会影响客户端的状态吗?
  • 我不这么认为,即使我不关闭流后它仍然会弹出此错误。 ://
  • @Bas 是的,它正在关闭导致错误 x) 的流
  • 您说错误发生在Send() 方法中,但您的代码没有显示对该方法的任何调用。你需要提供一个好的minimal reproducible example 来可靠地重现问题。也就是说,错误消息非常清楚:您试图在未连接的TcpClient 对象上调用GetStream(),即从未连接或已关闭。不要那样做。

标签: c# tcpclient


【解决方案1】:

client.GetStream() 的实现如下:

return new NetworkStream(this.Client, true);

而真正的意思是如果流被释放/关闭,它也会关闭/断开套接字/客户端。您应该可以通过直接调用来避免这种情况

var netStream = new NetworkStream(client.Client, false);

甚至更好的是:

NetworkStream netStream = client.GetStream();
…
netSteam.Dlose();

通过写入确保即使出现错误也始终关闭流:

using (var netStream = new NetworkStream(client.Client, false))
{
  …
}

【讨论】:

  • 确保流始终关闭的方法很棒。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-02-27
  • 1970-01-01
  • 1970-01-01
  • 2015-06-06
相关资源
最近更新 更多