Ejemplo n.º 1
1
        static void ProcessTcpClient(TcpClient client)
        {
            try
            {
                SslStream stream = new SslStream(client.GetStream());
                X509Certificate cert = new X509Certificate2(Certificate.CreateSelfSignCertificatePfx(
                    "CN=localhost", //host name
                    DateTime.Parse("2000-01-01"), //not valid before
                    DateTime.Parse("2099-01-01"), //not valid after
                    "mypassword"), "mypassword"); //password to encrypt key file)
                stream.AuthenticateAsServer(cert);

                byte[] requestBuffer = new byte[8192];
                int read = stream.Read(requestBuffer, 0, 8192);
                Array.Resize<byte>(ref requestBuffer, read);

                string request = Encoding.UTF8.GetString(requestBuffer);
                string requestedPath = request.Split('?')[0].Replace("GET ", "");

                Console.WriteLine(client.GetHashCode() + " => " + requestedPath);

                string response = "";

                if (requestedPath == "/gamepad/shardlist")
                {
                }
                else if (requestedPath == "/gamepad/lastshard")
                {
                }

                string header = "HTTP/1.1 200 OK\r\nDate: Fri, 10 Feb 2012 09:19:00 GMT\r\nServer: Apache/2.2.17 (Win32) mod_ssl/2.2.17 OpenSSL/0.9.8o\r\nContent-Length: " + response.Length + "\r\nContent-Type: text/html\r\n\r\n";

                byte[] headerBytes = Encoding.UTF8.GetBytes(header);
                byte[] responseBytes = Encoding.UTF8.GetBytes(response);
                stream.Write(headerBytes);
                stream.Flush();
                stream.Write(responseBytes);
                stream.Flush();
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception occured!\nMessage: " + e.Message + "\n" + e.StackTrace);
            }
        }
Ejemplo n.º 2
0
        public static void RemoveAction(this TcpClient client, Delegate action)
        {
            try
            {
                var key = client.GetHashCode();

                if (action is Action <byte[]> )
                {
                    if (tcp_received_actions.ContainsKey(key))
                    {
                        var temp = Delegate.RemoveAll(tcp_received_actions[key], action);
                        tcp_received_actions[key] = temp;
                    }
                }
                else
                {
                    if (tcp_closed_actions.ContainsKey(key))
                    {
                        var temp = Delegate.RemoveAll(tcp_closed_actions[key], action);
                        tcp_closed_actions[key] = temp;
                    }
                }
            }
            catch { }
        }
Ejemplo n.º 3
0
 public ClientHandler(TcpClient client,int id,GameHandler game)
 {
     Client = client;
     _game = game;
     FugamId = new FugamID(Client.GetHashCode(),id);
     _clientThread = new Thread(new ThreadStart(ClientThread));
     ServerIO.Send(Client.GetStream(),new PacketFugamID(FugamId));
 }
Ejemplo n.º 4
0
        public static void HandleReceive(TcpClient client)
        {
            LogHelper.ShowLog("Receive connect\t" + DateTime.Now.ToString() + "\t" +
             client.GetHashCode().ToString());

            Program.frmMainForm.delAddClient.Invoke(client);

            ClientConnection objClientConnection = new ClientConnection(client);
            objClientConnection.OnMessageReceived += new MessageReceive(OnReceive);
            objClientConnection.OnRemoteHostClosed += new RemoteHostClose(OnRemoteHostClose);
        }
Ejemplo n.º 5
0
        public SMTPRelayer(TcpClient tcpClient, SMTPSettings settings)
        {
            this.settings = settings;
            Console.WriteLine("Connected... {0}", tcpClient.GetHashCode());

            this.client_tcp = tcpClient;
            this.client_Stream = tcpClient.GetStream();

            this.server_tcp = new TcpClient(settings.RemoteAddress, settings.RemotePort);
            this.server_Stream = server_tcp.GetStream();

            this.readthread = new Thread(new ThreadStart(Read));
            this.writethread = new Thread(new ThreadStart(Write));
        }
Ejemplo n.º 6
0
        public Connection(TcpClient client, Player player)
        {
            _Client = client;
            IPString = _Client.Client.RemoteEndPoint.ToString();

            _Running = true;
            _TransmitQueue = new Queue<byte[]>();
            _Buffer = new byte[0];
            _Player = player;

            _Thread = new Thread(ConnectionThread);
            _Thread.Name = "SC-Player " + _Client.GetHashCode();
            _Thread.Start();
        }
Ejemplo n.º 7
0
        private void AddClient(TcpClient client)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new AddClientDelegate(AddClient), client);
            }
            else
            {
                ClientInfo info = new ClientInfo();
                info.ClientHost = client.GetHashCode().ToString();
                info.ConnectTime = DateTime.Now;

                lstClientInfo.Add(info);
                lstTcpClient.Add(client);

                bindingSource1.DataSource = lstClientInfo.ToArray();
                bindingSource1.Sort = "ConnectTime";

                LogHelper.ShowLog("Add Client\t" + info.ClientHost +
                    "\t Client List count:" + lstTcpClient.Count.ToString());
            }
        }
Ejemplo n.º 8
0
 public static void ClearActions(this TcpClient client)
 {
     try
     {
         var      key = client.GetHashCode();
         Delegate a;
         if (tcp_received_actions.TryRemove(key, out a))
         {
             a = null;
         }
         if (tcp_closed_actions.TryRemove(key, out a))
         {
             a = null;
         }
         CancellationTokenSource t;
         if (task_tokens.TryRemove(key, out t))
         {
             t.Cancel();
             t.Dispose();
         }
     }
     catch { }
 }
Ejemplo n.º 9
0
        private void RemoveClient(TcpClient client)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new RemoveClientDelegate(RemoveClient), client);
            }
            else
            {
                for (int i = 0; i < lstClientInfo.Count; i++)
                {
                    if (lstClientInfo[i].ClientHost == client.GetHashCode().ToString())
                    {
                        lstTcpClient.Remove(client);
                        lstClientInfo.RemoveAt(i);
                        break;
                    }
                }

                if (lstClientInfo.Count < 1)
                {
                    bindingSource1.Clear();
                }
                else
                {
                    bindingSource1.Clear();
                    bindingSource1.DataSource = lstClientInfo;
                }

                LogHelper.ShowLog("Remove Client\t" + client.GetHashCode().ToString() +
                    "\t Client List count:" + lstTcpClient.Count.ToString());
            }
        }
Ejemplo n.º 10
0
		public IAsyncResult BeginSend(string host, int port, bool useTls, string callingAe, string calledAe, AsyncCallback callback, object state) {
			_client = new TcpClient(host, port);
            //zssure:2015-04-14,try to conform whether AddRequest and Send uses the same one client
            LogManager.Default.GetLogger("Dicom.Network").Info("zssure debug at 20150414,the TcpClient object is {0},HashCode{1}", _client.ToString(),_client.GetHashCode()); 
            //zssure:2015-04-14,end

			if (Options != null)
				_client.NoDelay = Options.TcpNoDelay;
			else
				_client.NoDelay = DicomServiceOptions.Default.TcpNoDelay;

			Stream stream = _client.GetStream();

			if (useTls) {
				var ssl = new SslStream(stream, false, ValidateServerCertificate);
				ssl.AuthenticateAsClient(host);
				stream = ssl;
			}

			return BeginSend(stream, callingAe, calledAe, callback, state);
		}
Ejemplo n.º 11
0
        public static bool ConnectSocket(
           ref TcpClient client,
           string remoteHost,
           int remotePort,
            AsyncCallback asyncCallback)
        {
            try
            {
                #region main process

                if (client == null || client.Client == null)
                {
                    client = new TcpClient();
                }

                if (client.Connected)
                {
                    LogHelper.ShowLog("Re-Connect\t" + DateTime.Now.ToString() + "\t" +
                        "close current connect\t" + client.GetHashCode().ToString());

                    if (client.GetStream() != null)
                    {
                        client.GetStream().Close();
                    }

                    client.Close();
                    client = new TcpClient();

                    LogHelper.ShowLog("Create Client\t" + DateTime.Now.ToString() + "\t" +
                        client.GetHashCode().ToString());
                }

                try
                {
                    client.Connect(remoteHost, remotePort);
                }
                catch (ObjectDisposedException)
                {
                    client = new TcpClient();
                    client.Connect(remoteHost, remotePort);

                    LogHelper.ShowLog("Create Client\t" + DateTime.Now.ToString() + "\t" +
                        client.GetHashCode().ToString());
                }

                client.GetStream().BeginRead(readBuffer, 0,
                    READ_BUFFER_SIZE, asyncCallback, client);

                #endregion

                return true;
            }
            catch (SocketException ex)
            {
                if (client != null)
                {
                    client.Close();
                }

                ExceptionHelper.ShowException(ex);
            }
            catch (Exception ex)
            {
                if (client != null)
                {
                    client.Close();
                }

                ExceptionHelper.ShowException(ex);
            }

            return false;
        }
Ejemplo n.º 12
0
 public static void HandleReceive(TcpClient client, string data)
 {
     LogHelper.ShowLog("Receive\t\t" + DateTime.Now.ToString() + "\t" +
         client.GetHashCode().ToString() + "\t" + data);
 }
Ejemplo n.º 13
0
        public static void When(this TcpClient client, Action <byte[]> received, Action <IPEndPoint> closed)
        {
            var key = client.GetHashCode();

            if (received != null)
            {
                if (tcp_received_actions.ContainsKey(key))
                {
                    var temp = Delegate.Combine(tcp_received_actions[key], received);
                    tcp_received_actions[key] = temp;
                }
                else
                {
                    tcp_received_actions[key] = received;
                }
            }

            if (closed != null)
            {
                if (tcp_closed_actions.ContainsKey(key))
                {
                    var temp = Delegate.Combine(tcp_closed_actions[key], closed);
                    tcp_closed_actions[key] = temp;
                }
                else
                {
                    tcp_closed_actions[key] = closed;
                }
            }

            if (task_tokens.ContainsKey(key))
            {
                return;
            }

            var cts     = new CancellationTokenSource();
            var context = SynchronizationContext.Current;

            Task.Run(async() =>
            {
                while (true)
                {
                    try
                    {
                        var stream = client.GetStream();
                        if (cts.IsCancellationRequested)
                        {
                            break;
                        }
                        var data   = new byte[client.ReceiveBufferSize];
                        var length = await stream.ReadAsync(data, 0, data.Length);
                        if (length > 0 && tcp_received_actions.ContainsKey(key))
                        {
                            var temp = new byte[length];
                            Array.Copy(data, temp, length);
                            Array.Clear(data, 0, data.Length);
                            var a = tcp_received_actions[key];
                            context.Post(_ =>
                            {
                                try { a.DynamicInvoke(temp); }
                                catch { }
                            }, null);
                        }

                        if (tcp_closed_actions.ContainsKey(key))
                        {
                            var socket = client.Client;
                            if (socket.Poll(100, SelectMode.SelectRead) && socket.Available <= 0)
                            {
                                if (tcp_closed_actions.ContainsKey(key))
                                {
                                    var a = tcp_closed_actions[key];
                                    context.Post(_ =>
                                    {
                                        a.DynamicInvoke(socket.RemoteEndPoint);
                                    }, null);
                                }
                                ClearActions(client);
                                break;
                            }
                        }
                    }
                    catch
                    {
                        //if (tcp_closed_actions.ContainsKey(key))
                        //{
                        //    IPEndPoint p = null;
                        //    try
                        //    {
                        //        p = (IPEndPoint)client.Client.RemoteEndPoint;
                        //    }
                        //    catch { }
                        //    var a = tcp_closed_actions[key];
                        //    context.Post(_ =>
                        //                                {
                        //                                    a.DynamicInvoke(p);
                        //                                }, null);
                        //}
                        ClearActions(client);
                        break;
                    }
                }
            }, cts.Token).ConfigureAwait(false);
            task_tokens[key] = cts;
        }