2017-06-18 44 views
-1

我一直在創造這是假設的TcpClient連接到服務器,但我得到這個錯誤:的TcpClient錯誤:「System.InvalidOperationExceptio」

System.InvalidOperationException: 'The operation is not allowed on non-connected sockets.'

這裏是我的代碼:

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();的新實例時遇到錯誤。一直在努力尋找導致錯誤的原因,我認爲這是以某種方式關閉上面的連接。

一切都在一個類中,並且必須在軟件的任何位置調用。

+0

您連接時似乎正在關閉網絡流 - 是否會影響客戶端的狀態? – Bas

+0

我不這麼認爲,即使在它仍然彈出這個錯誤之後我沒有關閉流。 :/ –

+0

@Bas是它關閉導致錯誤的流x) –

回答

0

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)) 
{ 
    … 
} 
+0

確保流始終關閉使用的方式非常棒。謝謝 –