我需要一个C#层,它有助于在两个正在监听的TCP端口之间交换数据。
例如,有一个侦听器端口@ 192.168.1.2::5555和另一个侦听器端口@ 192.168.1.4::6666。
我能够使用socket.connect建立与两个侦听器的连接 我在创建2个线程时感到困惑 1 GT; Sock1.read() - >转换为字节 - > sock2 .write() 2 - ; Sock2.read() - >转换为字节 - > Sock1.write()
我认为这正在进入无限循环。是否有更好的方法通过建立与两个端口的连接在 2个侦听端口之间交换数据包?
我必须实现一个方法
Private void ExchangePackets(IpEndpoint ipe1,IpEndpoint ipe2)
{
//code here
}
答案 0 :(得分:2)
可能是这样的:(未经测试)
void ExchangePackets(IPEndPoint ipe1, IPEndPoint ipe2)
{
TcpClient tcp1 = new TcpClient();
tcp1.Connect(ipe1);
TcpClient tcp2 = new TcpClient();
tcp2.Connect(ipe2);
Task.Factory.StartNew(() => ByPass(tcp1, tcp2), TaskCreationOptions.LongRunning);
Task.Factory.StartNew(() => ByPass(tcp2, tcp1), TaskCreationOptions.LongRunning);
}
void ByPass(TcpClient tcp1, TcpClient tcp2)
{
using (tcp1)
using (tcp2)
{
Stream s1 = tcp1.GetStream();
Stream s2 = tcp2.GetStream();
byte[] buf = new byte[0x10000];
int len = s1.Read(buf, 0, buf.Length);
while (len > 0)
{
s2.Write(buf, 0, len);
len = s1.Read(buf, 0, buf.Length);
}
}
}
答案 1 :(得分:1)
$终于实现了它:-) $
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);
}
}
答案 2 :(得分:0)
编辑:经过仔细检查,我认为我的答案不适合您的情况。您的问题描述了许多可能阻止您以这种方式实施的固定约束。我会在这里留给其他人的答案,因为我认为这通常是正确的方法。
有没有更好的方法在2听之间交换数据包 端口是否与两个端口建立连接?
你不需要重新发明轮子:)
您可以使用WCF创建full-duplex TCP transport服务吗?