私は、tcpClient接続を介してデータを送信して、入力を受け取り、必要な操作を行うデバイスを操作しようとしています。サーバー上では、データはループで受信され、値は配列に設定されます。コードは次のようになります。はtcpClientを使用してデータを書き続けます
client = server.available();
//Receive Data
while(client.available()){
for(int i = 7; i<11; ++i){
String msg = client.readStringUntil('\n');
senddata[i] = msg.toInt();
msg ="";
}
私のクライアント側の機能は次のようになります。
static void Connect(String server, String message)
{
try
{
// Create a TcpClient.
// Note, for this client to work you need to have a TcpServer
// connected to the same address as specified by the server, port
// combination.
Int32 port = 85;
TcpClient client = new TcpClient(server, port);
// Translate the passed message into ASCII and store it as a Byte array.
Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
// Get a client stream for reading and writing.
// Stream stream = client.GetStream();
NetworkStream stream = client.GetStream();
// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length);
Console.WriteLine("Sent: {0}", message);
// Receive the TcpServer.response.
// Buffer to store the response bytes.
data = new Byte[256];
// String to store the response ASCII representation.
String responseData = String.Empty;
// Read the first batch of the TcpServer response bytes.
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine("Received: {0}", responseData);
// Close everything.
stream.Close();
client.Close();
}
catch (ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException: {0}", e);
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
Console.WriteLine("\n Press Enter to continue...");
Console.Read();
}
私のしたいが接続を閉じる前に連続してデータを書き込むことができ。基本的には次のようなものです:
int[] data = new int[4];
data[0] = 1;
data[0] = 1;
data[0] = 1;
data[0] = 1;
for (int i = 0; i < data.Length; i++)
{
Connect("192.168.1.125", data[i].ToString());
}
現在、データが送信され、接続が閉じられ、サーバーは処理するデータが増えません。私は別の解決策を試みたが運がない。
私は、ストリームにデータを書き込むループに以下のコードを実行しようとしている
編集:
for (int i = 0; i < 4; i++)
{
stream.Write(data, 0, data.Length);
Console.WriteLine("Sent: {0}", message);
// Receive the TcpServer.response.
// Buffer to store the response bytes.
data = new Byte[256];
// String to store the response ASCII representation.
String responseData = String.Empty;
// Read the first batch of the TcpServer response bytes.
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine("Received: {0}", responseData);
}
// Close everything.
stream.Close();
client.Close();
私は次のエラーを取得:)( Additional information: Unable to read data from the transport connection: An established connection was aborted by the software in your host machine.
クローズ要求をサーバ/クライアントから送られてくるまでも、あなたはクライアント側の接続をクローズしている、なぜオープン接続を維持しません:以下のコードのように、trueに設定するだけでTcpClient.NoDelayを修正するには? – Icepickle
サーバからの応答を読み込んだ直後に接続を終了しないと、データを書き込めないようです。私は何らかのエラーが発生する –
そのエラーを質問に追加するのはどうですか? – Icepickle