C#TCP流量重新路由

时间:2019-01-03 18:03:04

标签: c# tcp

因此,代码以一个IP地址和2个端口作为输入。第一个端口用于侦听器,而ip和第二个端口用于客户端。 例如,我想与浏览器连接,该程序将接收到的内容使用TcpClient发送到ip。然后从服务器接收并将接收到的内容发送回浏览器,然后重复该循环。基本上,该程序将我的请求重新发送到另一个ip,并将响应发送给我。

我已经尝试了2个线程,因此它与StreamWriters和阅读器是全双工的,并且不起作用。 我的代码:

public static void createServer(string ip, int port, int fakeport)
    {
        TcpListener ls = new TcpListener(IPAddress.Any, fakeport);
        ls.Start();
        TcpClient inner = ls.AcceptTcpClient();
        NetworkStream innerStream = inner.GetStream();
        StreamReader _sInnerStream = new StreamReader(innerStream, Encoding.ASCII);
        TcpClient serverClient = new TcpClient(ip, port);
        NetworkStream outerStream = serverClient.GetStream();
        StreamReader _sOuterStream = new StreamReader(outerStream, Encoding.ASCII);
        while (true)
        {
            string incomingInner = _sInnerStream.ReadLine();
            Console.WriteLine("Received from inner :" +incomingInner);
            byte[] buffer = Encoding.ASCII.GetBytes(incomingInner);
            // _rOuterStream.WriteLine(incomingInner);
            // _rOuterStream.Flush();
            innerStream.Write(buffer, 0, buffer.Length);

            string response = _sOuterStream.ReadLine();
            Console.WriteLine("Received response from outer :" + incomingInner);

            byte[] buffer1 = Encoding.ASCII.GetBytes(response);
            outerStream.Write(buffer1, 0, buffer1.Length);



        }
    }

任何帮助将不胜感激。

0 个答案:

没有答案