J'ai été la création d'un TCPClient qui est censé se connecter à un serveur, mais je reçois cette erreur:TCPClient Erreur: "System.InvalidOperationExceptio"
System.InvalidOperationException: 'The operation is not allowed on non-connected sockets.'
Voici mon code:
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
}
Je reçois et erreur lors de la création d'une nouvelle instance de NetworkStream netStream = client.GetStream();
. Été luttant pour trouver ce qui cause l'erreur, je pense que c'est en quelque sorte la fermeture de la connexion ci-dessus.
Tout est dans une classe et doit être appelée à n'importe où dans le logiciel.
Vous semblez fermer le flux de réseau lors de la connexion - cela influence-t l'état du client? – Bas
Je ne pense pas, même si je ne ferme pas le flux après que cette erreur soit encore présente. :/ –
@Bas Oui, c'est la fermeture du flux qui est à l'origine x d'erreur) –