private static dynamic genericWsCall(string tspUrl, string genType, string genTaskType, dynamic paras)
        {
            //client
            var serviceUrl = tspUrl;
            var binding    = new BasicHttpBinding();

            binding.Security.Mode = BasicHttpSecurityMode.Transport;
            binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
            var endpoint = new EndpointAddress(new Uri(serviceUrl));
            var client   = new WsClient(binding, endpoint);

            //prepare call
            Type       wsType   = Type.GetType(genType);
            MethodInfo wsMethod = wsType.GetMethod(genTaskType);
            dynamic    result;

            try
            {
                client.ClientCredentials.ClientCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindByThumbprint, "<Fingerprint>");
                client.OpenAsync().Wait();
                var task = (Task)wsMethod.Invoke(client, new object[] { paras });
                task.Wait();
                result = task.GetType().GetProperty("Result").GetValue(task);
                client.CloseAsync().Wait();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
                client.Abort();
                throw ex;
            }
            return(result);
        }
Example #2
0
        public static async Task Connect(string _ip, string _mac)
        {
            ip = _ip;
            Program.Print("IP: " + _ip);
            using (var client = await WsClient.ConnectAsync(new Uri("ws://" + ip))) {
                Program.Print("Uspjesno povezan.\n");
                _ = Listen(client);
                while (true)
                {
                    Program.Print($"§a{Program.PUBLIC_IP}§8@§c{_mac} §f$ ", true, false);
                    string Input = Console.ReadLine();

                    string[] Arg = Program.LineToArgs(Input);
                    if (Arg[0] == "exit")
                    {
                        return;
                    }
                    if (Arg[0] == "alan-desktop")
                    {
                        await client.SendStringAsync(Input.Substring(Arg[0].Length + 1));

                        return;
                    }
                    await client.SendStringAsync($"{{\"action\":\"terminal\",\"command\":\"{Input.Replace("\"", "\\\"")}\"}}");
                }
            }
        }
Example #3
0
 private void CmdConnect_Click(object sender, EventArgs e)
 {
     if (_connected) // Disconnect
     {
         if (_client == null)
         {
             _connected = false;
             UpdateButtons();
             return;
         }
         _client.CloseClientAsync();
     }
     else // Connect
     {
         if (int.TryParse(txtPort.Text, out int port))
         {
             if (!IsUriValid(txtServer.Text, port))
             {
                 return;
             }
             _client = new WsClient(txtServer.Text, int.Parse(txtPort.Text));
             _client.ConnectionStateChanged += Client_ConnectionStateChanged;
             _client.MessageReceived        += Client_MessageReceived;
             _client.ConnectionError        += Client_ConnectionError;
         }
         else
         {
             MessageBox.Show(this, LocalizedResourceHelper.GetLocalizedText(rm, "PortMustBeAnInteger", "Port must be an Integer"), LocalizedResourceHelper.GetLocalizedText(rm, "Error", "Error"), MessageBoxButtons.OK, MessageBoxIcon.Error);
         }
     }
     UpdateButtons();
 }
Example #4
0
        public async Task ValidateCryptoHandshake()
        {
            var     server = new WsServer();
            var     serverKey = CryptoExtensions.GenerateKey();
            var     clientKey = CryptoExtensions.GenerateKey();
            ECPoint serverPub, clientPub = new ECPoint();
            await server.StartAsync(new IPEndPoint(IPAddress.Loopback, 0), async stream =>
            {
                clientPub = await stream.EncryptAsync(serverKey);
            });

            await Task.Delay(500);

            // start client
            var client = new WsClient();
            var conn   = await client.ConnectAsync(new Uri($"ws://" + server.ListeningAddresses[0].Substring(7)));

            serverPub = await conn.EncryptAsync(clientKey);

            await Task.Delay(500);

            Assert.Equal(serverKey.Q.X, serverPub.X);
            Assert.Equal(clientKey.Q.X, clientPub.X);
            server.Dispose();
            client.Dispose();
        }
Example #5
0
 public override void _Ready()
 {
     server = "ws://127.0.0.1:8080/ws-chat/123?name=Hostname" + System.Guid.NewGuid();
     client = new WsClient(server);
     ConnectToServer();
     GD.Print("First");
 }
Example #6
0
        public async Task <IdResultDto <long> > AddRequestAsync <T>(T requestDto, WsClient wsClient)
            where T : AbstractRequestDto
        {
            IdResultDto <long> result = new IdResultDto <long>();

            // saving img to disk
            if (requestDto is PostDto)
            {
                PostDto post = requestDto as PostDto;
                TrimUserInfo(post.User);
                ProcessImage(post.Image);
            }

            // preparing request
            Request request = PrepareRequest(requestDto, wsClient);

            // saving to db
            long id = await _requestRepository.AddRequestAsync(request);

            // preparing result
            if (id > 0)
            {
                result.IsOk    = true;
                result.Id      = id;
                result.Message = "Request successfully added to queue.";
                result.Url     = _urlHelper.Link(requestDto.RouteName, new { id });
            }
            else
            {
                result.Message = "Something went wrong while adding request to db...";
            }

            return(result);
        }
Example #7
0
 public void Init()
 {
     //string hostname = Dns.GetHostName();
     //IPAddress[] adrList = Dns.GetHostAddresses(hostname);
     _client = new WsClient("ws://192.168.8.85:3000");
     //_client = new WsClient("ws://"+ adrList[1].ToString() + ":3000");
     _client.OnMessage = onMessage;
 }
    /// <summary>
    /// Unity method called on initialization
    /// </summary>
    private void Awake()
    {
        //gameController = GetComponent<GameController>();
        server = "ws://" + host + ":" + port;
        client = new WsClient(server);

        // Messaging
        GameMsg = new GameMessaging(this);
    }
Example #9
0
        /**
         * 建立链接
         * 发送消息
         * 接受消息
         * 打印日志
         */

        async Task LinkWs()
        {
            var wsAddress = WsAddressTBox.Text.Trim();

            wsClient?.Dispose();
            wsClient = await WsClient.ConnectAsync(new Uri(wsAddress));

            Console.WriteLine("建立链接!");
        }
Example #10
0
        private static async Task Listen(WsClient ws)
        {
            while (true)
            {
                string r = await ws.ReceiveStringAsync();

                //Program.Print(r);
            }
        }
Example #11
0
        public async Task Test()
        {
            // create the server
            var server    = new WsServer();
            var serverKey = CryptoExtensions.GenerateKey();
            var clientKey = CryptoExtensions.GenerateKey();

            Console.WriteLine($"Server key is: [{serverKey.Q.GetFingerprintString()}]");
            Console.WriteLine($"Client key is: [{clientKey.Q.GetFingerprintString()}]");
            await server.StartAsync(new IPEndPoint(IPAddress.Any, 8080), async stream =>
            {
                // encrypt
                // called when a client connects
                var br = new BinaryWriter(stream);
                var ct = Encoding.ASCII.GetBytes($"Hello from Server! {DateTime.Now}");
                br.Write(ct.Length);
                br.Write(ct);
                var res = await stream.EncryptAsync(serverKey);
                Console.WriteLine($"Client connected with fingerprint of [{res.GetFingerprintString()}]");
                while (stream.Connected)
                {
                    var bytes = Encoding.ASCII.GetBytes($"Hello from Server! {DateTime.Now}");
                    br.Write(bytes.Length);
                    br.Write(bytes);
                    await Task.Delay(1000);
                }
                await stream.CloseAsync();
            });

            // start client
            var client     = new WsClient();
            var connection = await client.ConnectAsync(new Uri("ws://localhost:8080"));

            // measure client data

            // read data
            var binReader = new BinaryReader(connection);
            int e         = binReader.ReadInt32();
            var g         = binReader.ReadBytes(e);

            Console.WriteLine(Encoding.ASCII.GetString(g));

            var serverRes = await connection.EncryptAsync(clientKey);

            Console.WriteLine($"Connected to server with fingerprint of [{serverRes.GetFingerprintString()}]");

            for (int i = 0; i < 100; i++)
            {
                int b         = binReader.ReadInt32();
                var bytesRead = binReader.ReadBytes(b);
                Console.WriteLine(Encoding.ASCII.GetString(bytesRead));
            }
            // cleanup
            client.Dispose();
            server.Dispose();
        }
Example #12
0
        private Request PrepareRequest(AbstractRequestDto requestDto, WsClient wsClient)
        {
            Request request = new Request();

            request.Type     = new RequestType(requestDto.RequestType);
            request.Input    = _utilsService.SerializeToJson(requestDto);
            request.WsClient = wsClient;

            return(request);
        }
Example #13
0
        public Task <IObservable <CurrentCandle> > SubscribeRealtimeQuoteAsync(ActivePair pair, TimeFrame tf)
        {
            WsClient?.SubscribeQuoteAsync(pair, tf).ConfigureAwait(false);

            var stream = WsClient?
                         .RealTimeCandleInfoObservable
                         .Where(x => x.ActivePair == pair && x.TimeFrame == tf);

            return(Task.FromResult(stream));
        }
Example #14
0
 private void Awake()
 {
     server = "ws://" + host + ":" + port + "/ws";
     try
     {
         client = new WsClient(server);
     }
     catch { }
     // ConnectToServer();
 }
        public Task <BinaryOptionsResult> BuyBinaryAsync(BuyModel buyModel)
        {
            OnBuy?.Invoke(buyModel);

            return(WsClient?.BuyBinaryAsync(
                       buyModel.Pair,
                       buyModel.Size,
                       buyModel.Direction,
                       buyModel.Expiration,
                       Profile.BalanceId));
        }
Example #16
0
 void Start()
 {
     //192.168.8.53 クァンのIP
     //192.168.11.17 クァンのパソコンip
     client = new WsClient("ws://192.168.43.253:4000");
     //string hostname = Dns.GetHostName();
     //IPAddress[] adrList = Dns.GetHostAddresses(hostname);
     //client = new WsClient("ws://" + adrList[1].ToString() + ":4000");
     client.OnMessage = onMessage;
     cameraOriPos     = Camera.main.transform.position;
 }
    public void Init()
    {
        isOwner = false;
        string time = string.Format("{0:yyyy-MM-dd HH-mm-ss}", DateTime.Now);

        logFileName = $"session_{time}.log";
        server      = (ssl ? "wss" : "ws") + "://" + host + ":" + port + "/" + path;
        client      = new WsClient(server);

        // Messaging
        Lobby = new LobbyMessaging(this);
    }
Example #18
0
        public async Task Test()
        {
            // create the server
            var server = new WsServer();
            await server.StartAsync(new IPEndPoint(IPAddress.Loopback, 8080), async stream =>
            {
                //await stream.EncryptAsync();
                Console.WriteLine($"Tunnel Opened: remote => localhost:12345");
                var sock = new Socket(SocketType.Stream, ProtocolType.Tcp);
                await sock.ConnectAsync("localhost", 12345);
                var ns = new NetworkStream(sock);
                var t1 = ns.CopyToAsync(stream, 62000);
                var t2 = stream.CopyToAsync(ns, 62000);
                await Task.WhenAny(t1, t2);
                sock.Dispose();
                await stream.DisposeAsync();
                Console.WriteLine($"Tunnel Closed: remote => localhost:25565");
            });

            Socket lSock = new Socket(SocketType.Stream, ProtocolType.Tcp);

            lSock.Bind(new IPEndPoint(IPAddress.Loopback, 1234));
            lSock.Listen(10);
            var cts = new CancellationTokenSource();

            Console.WriteLine($"Started... Listening to localhost:1234. Press ctrl + c to exit");
            Console.CancelKeyPress += (q, e) =>
            {
                cts.Cancel();
            };
            while (!cts.Token.IsCancellationRequested)
            {
                var ksock = await lSock.AcceptAsync();

                Task.Run(async() =>
                {
                    // start client
                    var client     = new WsClient();
                    var connection = await client.ConnectAsync(new Uri("ws://localhost:8080"));
                    //await connection.EncryptAsync();
                    var ns = new NetworkStream(ksock);
                    var t1 = ns.CopyToAsync(connection, 62000);
                    var t2 = connection.CopyToAsync(ns, 62000);
                    await Task.WhenAny(t1, t2);
                    ksock.Dispose();
                    await connection.DisposeAsync();
                    client.Dispose();
                });
            }
            // cleanup
            server.Dispose();
        }
        public async Task ReceiveStringWithCancel()
        {
            var _ = _webSocketServer.AcceptWebSocketAsync();

            using (var client = await WsClient.ConnectAsync(new Uri(_serverUrl)))
            {
                using (var cts = new CancellationTokenSource())
                {
                    cts.Cancel();
                    await Assert.ThrowsAsync <TaskCanceledException>(() => client.ReceiveStringAsync(cts.Token));
                }
            }
        }
Example #20
0
        /// <summary>
        ///     listen to all obs, for make all properties updated
        /// </summary>
        private void SubscribeWebSocket()
        {
            //subscribe profile
            HttpClient.ProfileObservable()
            .Merge(WsClient.ProfileObservable())
            .DistinctUntilChanged()
            .Where(x => x != null)
            .Subscribe(x => Profile = x);

            //subscribe for instrument updated
            WsClient.InstrumentResultSetObservable
            .Subscribe(x => Instruments = x);
        }
Example #21
0
        private async Task <IActionResult> ProcessRequestAsync <T>(T requestDto) where T : AbstractRequestDto
        {
            IActionResult result;

            string typeForLogs = typeof(T).Name;

            if (requestDto == null)
            {
                _logger.LogError("{0} Null input for '{1}'", LogDescription(), typeForLogs);
                result = BadRequest(new ResultDto {
                    Message = "Null input."
                });
            }
            else
            {
                // validating input
                MessageListResult validationResult = requestDto.Validate();

                if (!validationResult.IsOk)
                {
                    _logger.LogError("{0} ValidErr for '{1}': {2}",
                                     LogDescription(), typeForLogs, validationResult.Message);
                    ResultDto badValidationResult = _mapper.Map <ResultDto>(validationResult);
                    result = BadRequest(badValidationResult);
                }
                else
                {
                    // getting wsClient
                    WsClient wsClient = await GetWsClient();

                    // adding request to queue
                    IdResultDto <long> addResult = await _requestService.AddRequestAsync(requestDto, wsClient);

                    if (addResult.IsOk)
                    {
                        _logger.LogDebug("{0} Ok for: '{1}' -> Id: '{2}'",
                                         LogDescription(), typeForLogs, addResult.Id);
                        result = Ok(addResult);
                    }
                    else
                    {
                        // when ID from DB <= 0
                        _logger.LogError("{0} Error for: '{1}' -> Message: '{2}'",
                                         LogDescription(), typeForLogs, addResult.Message);
                        result = InternalServerError(addResult);
                    }
                }
            }

            return(result);
        }
        public async Task ServerCloseFirst()
        {
            var serverTask = _webSocketServer.AcceptWebSocketAsync();
            var client     = await WsClient.ConnectAsync(new Uri(_serverUrl));

            var server = await serverTask;

            await server.CloseAsync(WebSocketCloseStatus.NormalClosure, null, CancellationToken.None);

            client.Dispose();
            await client.CloseTask;

            Assert.Null(client.CloseException);
        }
Example #23
0
        public void Initialize(string id, string ipAddress, ushort port, string macAddress)
        {
            _isBusy = true;
            if (onBusy != null)
            {
                onBusy(1);
            }

            _id         = id;
            _ipAddress  = ipAddress;
            _port       = port;
            _macAddress = Regex.Replace(macAddress, "[-|:]", "");

            var currentDirectory = Directory.GetApplicationDirectory().Split('\\');

            _keyFilePath = string.Format(@"\User\{0}\lgWebOsDisplay_{1}", currentDirectory[2], _id);

            if (File.Exists(_keyFilePath))
            {
                using (StreamReader reader = new StreamReader(File.OpenRead(_keyFilePath)))
                {
                    _clientKey = reader.ReadToEnd().Replace("\r\n", string.Empty);
                }
            }

            _mainClient = new WsClient();

            _mainClient.ID            = "LgWebOs - " + _id;
            _mainClient.AutoReconnect = 1;

            if (_debugMode)
            {
                _mainClient.DebugMode = 1;
            }

            _mainClient.ConnectionStatusChange += new EventHandler <ConnectionEventArgs>(_mainClient_ConnectionStatusChange);
            _mainClient.ReceiveDataChange      += new EventHandler <ReceiveDataEventArgs>(_mainClient_ReceiveDataChange);

            _udpServer = new UDPServer(_ipAddress, 40000, 1000);
            _udpServer.EthernetAdapterToBindTo = EthernetAdapterType.EthernetLANAdapter;
            _udpServer.EnableUDPServer();

            _isBusy = false;
            if (onBusy != null)
            {
                onBusy(0);
            }

            Connect();
        }
Example #24
0
        public async void Handshaking(TcpClient client)
        {
            NetworkStream networkStream = client.GetStream();

            byte[] bufferReceive = new byte[client.Available];
            await networkStream.ReadAsync(bufferReceive, 0, bufferReceive.Length);

            string[] request = Encoding.ASCII.GetString(bufferReceive).Split(Environment.NewLine);

            Dictionary <string, string> headers = new Dictionary <string, string>();

            headers.Add("method", request[0]);

            for (int i = 1; i < request.Length - 2; i++)
            {
                if (request[i].Contains(':'))
                {
                    Console.WriteLine(request[i]);

                    string[] values = request[i].Split(':');

                    headers.Add(values[0].ToLower(), values[1].TrimStart());
                }
            }

            if (headers["method"].StartsWith("GET"))
            {
                string response = "HTTP/1.1 101 Switching Protocols" + Environment.NewLine;
                response += "Connection: Upgrade" + Environment.NewLine;
                response += "Upgrade: websocket" + Environment.NewLine;

                byte[] hash = SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(headers["Sec-WebSocket-Key"] + _shaKey));
                response += "Sec-WebSocket-Accept: " + Convert.ToBase64String(hash);

                response += Environment.NewLine + Environment.NewLine;

                Console.WriteLine();
                Console.WriteLine(response);

                byte[] bufferSend = Encoding.UTF8.GetBytes(response);

                await networkStream.WriteAsync(bufferSend, 0, bufferSend.Length);
            }

            WsClient wsClient = new WsClient(client);

            _server.OnClientConnect(wsClient);
        }
        public async Task SendDataWithDifferentLengths(int length)
        {
            var serverTask = _webSocketServer.AcceptWebSocketAsync();

            using (var client = await WsClient.ConnectAsync(new Uri(_serverUrl)))
            {
                var    server = await serverTask;
                byte[] data   = new byte[length];
                await client.SendByteArrayAsync(data);

                var buffer = new ArraySegment <byte>(new byte[length]);
                WebSocketReceiveResult result = await server.ReceiveAsync(buffer, CancellationToken.None);

                Assert.True(length == result.Count);
            }
        }
        public async Task ReceiveDataWithDifferentLengths(int length)
        {
            var serverTask = _webSocketServer.AcceptWebSocketAsync();

            using (var client = await WsClient.ConnectAsync(new Uri(_serverUrl)))
            {
                var    server = await serverTask;
                byte[] data   = new byte[length];
                var    buffer = new ArraySegment <byte>(data);
                await server.SendAsync(buffer, WebSocketMessageType.Binary, true, CancellationToken.None);

                var receivedMsg = await client.ReceiveByteArrayAsync();

                Assert.True(length == receivedMsg.Length);
            }
        }
        public async Task ClientCloseFirst()
        {
            var serverTask = _webSocketServer.AcceptWebSocketAsync();
            var client     = await WsClient.ConnectAsync(new Uri(_serverUrl));

            var server = await serverTask;

            // let server respond to client's close frame
            var serverCloseTask = server.ReceiveAsync(new ArraySegment <byte>(new byte[1024]), CancellationToken.None);

            client.Dispose();
            await serverCloseTask;
            await client.CloseTask;

            Assert.Null(client.CloseException);
        }
        public async Task ReceiveStringOK()
        {
            var serverTask = _webSocketServer.AcceptWebSocketAsync();

            using (var client = await WsClient.ConnectAsync(new Uri(_serverUrl)))
            {
                var    server  = await serverTask;
                string sendMsg = "Hi!";
                var    buffer  = new ArraySegment <byte>(Encoding.UTF8.GetBytes(sendMsg));
                await server.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);

                string receivedMsg = await client.ReceiveStringAsync();

                Assert.True(sendMsg == receivedMsg);
            }
        }
Example #29
0
        static void Main(string[] args)
        {
            WsClient.Open();
            while (true)
            {
                Console.WriteLine("type whatever to send. press q+Enter to stop");
                var read = Console.ReadLine();
                if (read == "q")
                {
                    break;
                }

                WsClient.Send(read);
            }

            WsClient.Close();
        }
        public async Task SendStringOK()
        {
            var serverTask = _webSocketServer.AcceptWebSocketAsync();

            using (var client = await WsClient.ConnectAsync(new Uri(_serverUrl)))
            {
                var    server  = await serverTask;
                string message = "Hi!";
                await client.SendStringAsync(message);

                var buffer = new ArraySegment <byte>(new byte[1024]);
                WebSocketReceiveResult result = await server.ReceiveAsync(buffer, CancellationToken.None);

                Assert.True(result.MessageType == WebSocketMessageType.Text);
                Assert.True(message == Encoding.UTF8.GetString(buffer.Array, 0, result.Count));
            }
        }
	// Use this for initialization
	void Awake () {
		// Initialize services and variables
		game = Game.Instance;
		wsc = WsClient.Instance;

		generalList = Generals.GetList (1001);
		numberOfGenerals = generalList.Count;

		counselorList = Counselors.GetList (1);
		numberOfCounselors = counselorList.Count;

		Debug.Log ("Number of counselors: " + numberOfCounselors);
		Debug.Log ("Number of generals: " + numberOfGenerals);


		wsc.conn.OnMessage += (sender, e) => { 
			Debug.Log (e.Data);
			var j = JSON.Parse(e.Data);

			switch ((jsonFuncNumberEnum)j["func"].AsInt){
			case jsonFuncNumberEnum.getUserInformationByUserId:
				game.login = new Login((JSONClass)j["obj"]);
				break;
			case jsonFuncNumberEnum.getPrivateChatHistories:
				var jArray = j["obj"];
				Debug.Log(j["obj"][1]["message"]);
				break;
			default:
				break;
			}
		};


		wsc.conn.OnError += (sender, e) => {
			Debug.LogError (e.Message);
		};
	}