$终于实现了:-) $
private void Form1_Load(object sender, EventArgs e)
{
RoutingClient=new TcpClient("127.0.0.1",5765);
ServerClient = new TcpClient("127.0.0.1", 5766);
rcStream = RoutingClient.GetStream();
ScStream = ServerClient.GetStream();
//start 2 threads
Thread t1 = new Thread(()=>ExchangePackets(rcStream,ScStream));
t1.Start();
Thread t2 = new Thread(() => ExchangePackets(ScStream, rcStream));
t2.Start();
}
private static void ExchangePackets(NetworkStream FirstStream, NetworkStream SecondStream)
{
try
{
while (true)
{
if (FirstStream.CanRead)
{
byte[] myReadBuffer = new byte[1024];
StringBuilder myCompleteMessage = new StringBuilder();
MemoryStream ms = new MemoryStream();
int numberOfBytesRead = 0;
int TotalBytesRead = 0;
// Incoming message may be larger than the buffer size.
do
{
numberOfBytesRead = FirstStream.Read(myReadBuffer, 0, myReadBuffer.Length);
ms.Write(myReadBuffer, TotalBytesRead, numberOfBytesRead);
myCompleteMessage.AppendFormat("{0}", Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead));
TotalBytesRead = TotalBytesRead + numberOfBytesRead;
}
while (FirstStream.DataAvailable);
MessageBox.Show("You received the following message : " +
myCompleteMessage);
if (SecondStream.CanWrite)
{
byte[] myWriteBuffer = ms.ToArray();
SecondStream.Write(myWriteBuffer, 0, myWriteBuffer.Length);
}
else
{
MessageBox.Show("Sorry. You cannot write to this NetworkStream.");
}
}
else
{
MessageBox.Show("Sorry. You cannot read from this NetworkStream.");
}
}
}
catch (Exception ex)
{
MessageBox.Show("Routing to Server:" + ex.Message);
}
}