我有一个监听我的消息的服务器,从15到15秒,它发送一个保持活动消息 我需要实现一个客户端,它将消息发送到服务器并持续监听 我在不同的线程上使用流编写器和读取器 问题是我需要编写不同的消息并听取相应的响应,然后我需要发送保持活动的消息。如果不是,则远程主机中止连接。
public static void main(){
Connect(tcpClient1,port1,stream1);
connectDone.WaitOne();
Connect(tcpClient2, port1,stream2);
connectDone.WaitOne();
Connect(tcpClient3,port1,stream1);
connectDone.WaitOne();
writeThread = new Thread(() => Send(tcpClient1,stream1));
writeThread.Start();
sendDone.WaitOne();
readThread = new Thread(() => Read(tcpClient2,stream2));
readThread.Start();
receiveDone.WaitOne();
Console.ReadKey();
}
public static void Send(TcpClient tcpClient,NetworkStream stream)
{
try
{
stream = tcpClient.GetStream();
int i, j = 0;
while (tcpClient.Connected)
{
StreamWriter sw = new StreamWriter(stream);
Console.WriteLine("Write your index for the message:");
while (true)
{
Console.Write("Enter the Integer Number : ");
if (int.TryParse(Console.ReadLine(), out i))
{
break;
}
Console.WriteLine("Please enter an integer value!");
}
if (stream.CanWrite)
{
lock (stream)
{
Console.WriteLine("Transmitting.....");
sw.WriteLineAsync(DPLHeader(Messages.ElementAt(i)));
sw.Flush();
Thread.Sleep(23000);
sendDone.Set();
Console.WriteLine("Sent to server the message.");
}
}
j++;
}
}
public static void Read(TcpClient tcpClient, NetworkStream stream)
{
try
{
int i = 0;
stream = tcpClient.GetStream();
// stream.ReadTimeout = 100;
while (tcpClient.Connected)
{
/*if (i != 0)
{
receiveDone.Reset();
}*/
StreamReader sr = new StreamReader(stream);
if (stream.CanRead && stream.DataAvailable)
{
lock (stream)
{
while (sr.Peek() > -1)
{
response = sr.ReadLine();
}
receiveDone.Set();
Console.WriteLine("Received..." + response);
List<string> list = Decode(DecodingMsg(response));
SendToText(list);
}
}
i++;
}
}