123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- using System;
- using System.Net;
- using System.Net.Sockets;
- using System.Net.WebSockets;
- using System.Threading;
- using System.Threading.Tasks;
- namespace WebSocketForwardClient
- {
- internal class Program
- {
- private static string _url;
- private const int KiB = 1024;
- private const int MiB = 1024 * KiB;
- private const int BufferSize = MiB;
- private static void Main(string[] args)
- {
- _url = args[0];
- var fwSvr = new TcpListener(IPAddress.Any, int.Parse(args[1]));
- fwSvr.Start();
- Console.WriteLine("Listening on: " + fwSvr.Server.LocalEndPoint);
- while (true)
- {
- var handleRequest = HandleRequest(fwSvr.AcceptTcpClient());
- }
- }
- private static int _connectionId = 0;
- private static async Task HandleRequest(TcpClient client)
- {
- var cid = Interlocked.Increment(ref _connectionId);
- Console.WriteLine($"#{cid} Accept From: " + client.Client.RemoteEndPoint);
- var ws = new ClientWebSocket();
- try
- {
- await ws.ConnectAsync(new Uri(_url), CancellationToken.None);
- }
- catch (Exception e)
- {
- Console.WriteLine($"#{cid} Connection error: {e}");
- client.Close();
- return;
- }
- Console.WriteLine($"#{cid} Connected ");
- var ns = client.GetStream();
- var tIn = Task.Run(async () =>
- {
- var buf = new byte[BufferSize];
- var arrSeg = new ArraySegment<byte>(buf);
- while (true)
- {
- var r = await ws.ReceiveAsync(arrSeg, CancellationToken.None);
- await ns.WriteAsync(buf, 0, r.Count);
-
- if (r.Count == 0) break;
- }
- });
- var tOut = Task.Run(async () =>
- {
- var buf = new byte[BufferSize];
- while (true)
- {
- var count = await ns.ReadAsync(buf, 0, buf.Length);
- var arrSeg = new ArraySegment<byte>(buf, 0, count);
- await ws.SendAsync(arrSeg, WebSocketMessageType.Binary, true, CancellationToken.None);
-
- }
- });
- Task.WaitAny(tIn, tOut);
- client.Close();
- }
- }
- }
|