예제 #1
0
 public DemoForMySocket()
 {
     ms = new MyTcpClient("192.168.78.110:60000");
     ms.OnReceiveData         += ms_OnReceiveData;
     ms.OnTcpConnected        += ms_OnTcpConnected;
     ms.OnTcpConnectionLosted += ms_OnTcpConnectionLosted;
 }
예제 #2
0
        public static void SendMessage(string message, MyTcpClient currentClient)
        {
            NetworkStream nws = currentClient.TcpClient.GetStream();

            byte[] msg = Encoding.UTF8.GetBytes(message);
            nws.Write(msg, 0, msg.Length);
        }
        private void myDirectionalTestForDevEpAdd_Load(object sender, EventArgs e)
        {
            isTest     = false;
            mywaitTime = 10;
            myTimeOut  = setTimeOut;
            comboBox_waitTime.SelectedIndex = 0;
            //class
            nowVaneConfigRequestData = new myVaneConfigRequestData();
            myBeatTimer.Interval     = 20000;
            myBeatTimer.Tick        += new EventHandler(myBeatTimer_Tick);

            //set the from name
            this.Text += ("  " + myIpEp.Address.ToString());

            nowSocket = new MyTcpClient(myIpEp, 500);
            if (!nowSocket.IsTcpClientConnected)
            {
                if (nowSocket.Connect())
                {
                    nowSocket.OnReceiveData         += new MyTcpClient.delegateReceiveData(nowSocket_nowReceiveData);
                    nowSocket.OnTcpConnectionLosted += new MyTcpClient.ConnectionLosted(nowSocket_OnTcpConnectionLosted);
                    myBeatTimer.Enabled              = true;
                    addMessage("coonect success");
                }
                else
                {
                    MessageBox.Show(nowSocket.ErroerMessage);
                    this.Close();
                }
            }
        }
예제 #4
0
        private static void HandleConnection(MyTcpClient currentClient)
        {
            while (currentClient.TcpClient.Connected)
            {
                try
                {
                    NetworkStream nws        = currentClient.TcpClient.GetStream();
                    byte[]        readBuffer = new byte[currentClient.TcpClient.ReceiveBufferSize];
                    int           streamSize = -1;
                    while ((streamSize = nws.Read(readBuffer, 0, readBuffer.Length)) != 0)
                    {
                        string recievedData = Encoding.UTF8.GetString(readBuffer, 0, streamSize);
                        Console.WriteLine("Message Recieved: " + recievedData);
                        string commandValue = ParseCommand(recievedData, currentClient);

                        //send only back to the guy you recieved data from
                        //SendMessage(commandValue, currentClient);

                        //If you want to send out the recieved message to all connected clients,
                        //Loop over the "clients" collection and do a SendMessage(msg, client)
                        foreach (var client in clients.Values.Where(x => x != currentClient))
                        {
                            SendMessage(recievedData, client);
                        }
                    }
                }
                catch (Exception ex)
                {
                    MyTcpClient exit;
                    clients.TryRemove(currentClient.ClientId, out exit);
                    exit.TcpClient.Close();
                    Console.WriteLine(ex.Message);
                }
            }
        }
예제 #5
0
 public void Dispose()
 {
    if ( _tcpClient != null )
    {
       _tcpClient.Close();
       _tcpClient = null;
    }
 }
예제 #6
0
 public PrivateChatForm(string displayName, string userName, MyTcpClient client)
 {
     _displayName = displayName;
     _userName    = userName;
     _client      = client;
     InitializeComponent();
     Text = "与(" + _displayName + ")的聊天";
 }
예제 #7
0
 public void Dispose()
 {
     if (_tcpClient != null)
     {
         _tcpClient.Close();
         _tcpClient = null;
     }
 }
예제 #8
0
        public Form1()
        {
            InitializeComponent();
            var binding  = new NetTcpBinding(SecurityMode.None, false);
            var endpoint = new EndpointAddress(ConfigurationManager.AppSettings["ServerAddress"]);

            _tcpClient = new MyTcpClient(binding, endpoint);
            _synchronizationContext = WindowsFormsSynchronizationContext.Current;
        }
예제 #9
0
 public MyDataComunication OpenCommunication(string ipAddress, Action <object> callbackDataForImageProcessing)
 {
     ImageServer = new MyTcpServer(NetworkConstants.LocalLisenerConnection, 27001);
     ImageClient = new MyTcpClient(ipAddress, 27001);
     VoiceClient = new MyUdpClient(ipAddress, 27000);
     VoiceServer = new MyUdpServer(NetworkConstants.LocalLisenerConnection, 27000);
     ReciveImageAndProcess(callbackDataForImageProcessing);
     GrabImageAndSend();
     RecordSoundAndSend();
     ReceiveAndPlaySound();
     return(this);
 }
예제 #10
0
        public void ListenForConnections()
        {
            //start server
            Server.Start();

            //listen for incoming connection and start a thread that handels the connection (functioon processconnection)
            while (true)
            {
                IMyTcpClient client = new MyTcpClient(Server.AcceptTcpClient());
                Thread       threadToProcessClient = new Thread(delegate() { ProcessConnection(client); });
                threadToProcessClient.Start();
            }
        }
예제 #11
0
        private void MyVaneConfig_Load(object sender, EventArgs e)
        {
            //cantrol and vaule
            splitContainer_orderForm.FixedPanel = System.Windows.Forms.FixedPanel.Panel1;
            myMaxLine = ((AutoRunner)(this.Parent.Parent.Parent.Parent)).MaxLine;
            cb_verUpgradeRequest_verType.SelectedIndex = 0;
            isMyAlive = true;
            this.Activate();
            //class
            nowVaneConfigRequestData = new myVaneConfigRequestData();
            myBeatTimer.Interval     = 20000;
            myBeatTimer.Tick        += new EventHandler(myBeatTimer_Tick);
            //test
            Thread myThread = new Thread(new ParameterizedThreadStart(newTestThread));

            myThread.IsBackground = true;
            myThread.Start("");

            //set the from name
            this.Text += ("  " + myIpEp.Address.ToString());
            nowSocket  = new MyTcpClient(myIpEp, 500);
            if (!nowSocket.IsTcpClientConnected)
            {
                if (nowSocket.Connect())
                {
                    nowSocket.OnReceiveData         += new MyTcpClient.delegateReceiveData(nowSocket_nowReceiveData);
                    nowSocket.OnTcpConnectionLosted += new MyTcpClient.ConnectionLosted(nowSocket_OnTcpConnectionLosted);
                    myBeatTimer.Enabled              = true;
                    MyPutInKey keyWindow = new MyPutInKey();
                    keyWindow.Owner         = this;
                    keyWindow.StartPosition = FormStartPosition.CenterParent;
                    keyWindow.ShowDialog();
                    {
                        if (isKeyNeed)
                        {
                            //MessageBox.Show(myGwKey);
                            doConfiguration(myGwKey);
                        }
                        else
                        {
                            MessageBox.Show("NOT FIND THE KEY");
                        }
                    }
                }
                else
                {
                    MessageBox.Show(nowSocket.ErroerMessage);
                    this.Close();
                }
            }
        }
예제 #12
0
        private static string ParseCommand(string cmd, MyTcpClient currentClient)
        {
            //command pattern: command0 = what to do --> command1: arguments for first command
            string[] commands = cmd.Split(' ');

            if (commands.Length >= 2)
            {
                switch (commands[0])
                {
                case "weather":
                    return(GetWeatherInfo(commands[1]));

                    break;

                case "start":
                    return(OpenApplication(commands));

                    break;

                case "move":
                    return(MoveCursor());

                    break;

                case "process":
                    return(GetRunningProcesses(commands[1]));

                    break;

                case "direction":
                    return(GetDirectionsFor(commands[1], commands[2]));

                    break;

                case "person":
                    CreatePerson(commands[1], commands[2], commands[3], currentClient);
                    return("Added");

                    break;

                default:
                    return("Command could not be recognized");

                    break;
                }
            }
            return("Command could not be parsed");
        }
예제 #13
0
        /// <summary>
        /// Creates a channel to the given address. This will setup the TCP connection.
        /// </summary>
        /// <param name="remoteAddress">The remote address.</param>
        /// <param name="connectionTimeoutMillis">The timeout for establishing a TCP connection.</param>
        /// <param name="handlers">The handlers to be added to the channel's pipeline.</param>
        /// <returns></returns>
        public MyTcpClient CreateTcp(IPEndPoint remoteAddress, int connectionTimeoutMillis, IDictionary <string, IChannelHandler> handlers)
        {
            _readWriteLockTcp.EnterReadLock();
            try
            {
                if (_shutdownTcp)
                {
                    return(null);
                }
                // try to acquire resources for the channel
                if (_semaphoreTcp == null || !_semaphoreTcp.TryAcquire())
                {
                    const string errorMsg = "Tried to acquire more resources (TCP) than announced.";
                    Logger.Error(errorMsg);
                    throw new SystemException(errorMsg);
                }

                // create and bind
                var pipeline         = new Pipeline(handlers);
                var filteredPipeline = _channelClientConfiguration.PipelineFilter.Filter(pipeline, true, true);

                var tcpClient = new MyTcpClient(_externalBindings.WildcardSocket(), filteredPipeline);
                _recipients.Add(tcpClient);
                SetupCloseListener(tcpClient, _semaphoreTcp);

                // TODO how to set CONNECT_TIMEOUT_MILLIS option?
                tcpClient.Socket.NoDelay     = true;
                tcpClient.Socket.LingerState = new LingerOption(false, 0);
                tcpClient.Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

                // connect
                try
                {
                    tcpClient.ConnectAsync(remoteAddress).Wait();
                }
                catch (Exception ex)
                {
                    Logger.Warn(ex);
                    throw;
                }

                return(tcpClient);
            }
            finally
            {
                _readWriteLockTcp.ExitReadLock();
            }
        }
예제 #14
0
      public Stream Connect(IBrokerInfo broker)
      {
         MCertificate cert = GetClientCert(broker);
         SecurityOptions options = new SecurityOptions(
            SecureProtocol.Tls1, cert, ConnectionEnd.Client
            );
         if ( broker.SslOptions != null 
            && broker.SslOptions.IgnoreValidationErrors )
         {
            _logger.Warn("Ignoring any certificate validation errors during SSL handshake...");
            options.VerificationType = CredentialVerification.None;
         }

         _tcpClient = new MyTcpClient(broker.Host, broker.Port, options);
         return _tcpClient.GetStream();
      }
        public void Start(ServerDatas gameServerDatas, ServerDatas mmServerDatas, Func <Match, ServerGameMaster> createGameMaster, bool debug = false)
        {
            this.debug = debug;
            Server     = new MyUdpServer();
            string udpAddress = CliArguments.GetArgument("--address");
            string udpPort    = CliArguments.GetArgument("--port");

            Server.Start(udpAddress != null ? udpAddress : gameServerDatas.address, udpPort != null ? int.Parse(udpPort) : gameServerDatas.port, debug);
            Client = new MyTcpClient();
            string mmAddress = CliArguments.GetArgument("--mmaddress");
            string mmPort    = CliArguments.GetArgument("--mmport");

            Client.Start(mmAddress != null ? mmAddress : mmServerDatas.address, mmPort != null ? int.Parse(mmPort) : mmServerDatas.port, OnMMReady, OnConnectionFail, debug);
            _createGameMaster = createGameMaster;
            _defaultWorld     = World.DefaultGameObjectInjectionWorld;
        }
예제 #16
0
        private void openConnection()
        {
            String api_addr = LE_API;

            try
            {
                this.socket = new MyTcpClient(LE_API, Ssl);

                String header = String.Format("PUT /{0}/hosts/{1}/?realtime=1 HTTP/1.1\r\n\r\n", this.SubstituteAppSetting(CONFIG_KEY), this.SubstituteAppSetting(CONFIG_LOCATION));
                this.socket.Write(ASCII.GetBytes(header), 0, header.Length);
            }
            catch
            {
                throw new IOException();
            }
        }
예제 #17
0
 private void ButtonCall_Click(object sender, EventArgs e)
 {
     if (Global.ValidateIPv4(GetAddress()))
     {
         if (Global.GetLocalIPAddress() != GetAddress())
         {
             if (!locked)
             {
                 DialogResult dialogResult = MessageBox.Show(String.Format("Are you sure you want to call {0}?", Global.GetContactName(GetAddress())), "", MessageBoxButtons.YesNo);
                 if (dialogResult == DialogResult.Yes)
                 {
                     myTcpClient = new MyTcpClient(GetAddress());
                     LockUI('c');
                     ticks          = 0;
                     timer1.Enabled = true;
                 }
             }
             else
             {
                 try
                 {
                     PSSP pssp = new PSSP(PSSP.Type.END);
                     MyTcpClient.client.GetStream().Write(pssp.ToBytes(), 0, pssp.ToBytes().Length);
                     myTcpClient.sp.Stop();
                     Global.AddtoHistory(new HistoryRecord(new Contact("Me", Global.GetLocalIPAddress()).ToString(), "->", new Contact(Global.GetContactName(GetAddress()), GetAddress()).ToString(), DateTime.Now, "00:00:00", "Missed"));
                     UnlockUI();
                     DisableTimer();
                 }
                 catch (Exception ex)
                 {
                     Console.WriteLine(ex);
                     myTcpClient.Stop();
                     UnlockUI();
                     DisableTimer();
                 }
             }
         }
         else
         {
             MessageBox.Show("You can't call to yourself!");
         }
     }
     else
     {
         MessageBox.Show("Invalid address!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
예제 #18
0
        public Stream Connect(IBrokerInfo broker)
        {
            MCertificate    cert    = GetClientCert(broker);
            SecurityOptions options = new SecurityOptions(
                SecureProtocol.Tls1, cert, ConnectionEnd.Client
                );

            if (broker.SslOptions != null &&
                broker.SslOptions.IgnoreValidationErrors)
            {
                _logger.Warn("Ignoring any certificate validation errors during SSL handshake...");
                options.VerificationType = CredentialVerification.None;
            }

            _tcpClient = new MyTcpClient(broker.Host, broker.Port, options);
            return(_tcpClient.GetStream());
        }
예제 #19
0
        public String RunBackground()
        {
            NetworkStream stream = MyTcpClient.InitializeConnection(null, null);

            if (stream == null)
            {
                return("Could not connect to the default server");
            }
            if (!_commandsQueueThread.IsAlive)
            {
                _commandsQueueThread.Start();
            }

            Thread clientThread = new Thread(() => MyTcpClient.CreateAndRunClient(stream));

            clientThread.Start();
            return(null);
        }
예제 #20
0
        public static void StartAcceptingClient(TcpListener srv)
        {
            while (true)
            {
                srv.Start();
                var currentClient = new MyTcpClient();
                currentClient.TcpClient = srv.AcceptTcpClient();//Blocking call
                lock (ClientAmountLock)
                {
                    currentClient.ClientId = ClientAmount;
                    clients.TryAdd(ClientAmount, currentClient);
                    ClientAmount++;
                }

                Thread t = new Thread(() => HandleConnection(currentClient)); //constantly read the stream; blocking so in a thread
                t.Start();
            }
        }
예제 #21
0
        /// <summary>
        /// Decodes a message from the provided byte array.
        /// </summary>
        /// <param name="bytes">The message bytes from Java encoding.</param>
        /// <returns>The .NET message version.</returns>
        public static Message DecodeMessage(byte[] bytes)
        {
            var decoder = new Decoder(null);

            // mock a non-working ChannelHandlerContext
            var pipeline = new Pipeline();
            var channel  = new MyTcpClient(new IPEndPoint(IPAddress.Any, 0), pipeline);
            var session  = new PipelineSession(channel, pipeline, new List <IInboundHandler>(), new List <IOutboundHandler>());
            var ctx      = new ChannelHandlerContext(channel, session);

            // create dummy sender for decoding
            var message = Utils2.CreateDummyMessage();
            AlternativeCompositeByteBuf buf = AlternativeCompositeByteBuf.CompBuffer();

            buf.WriteBytes(bytes.ToSByteArray());
            decoder.Decode(ctx, buf, message.Recipient.CreateSocketTcp(), message.Sender.CreateSocketTcp());

            return(decoder.Message);
        }
예제 #22
0
 void CreateGameSignaling(MyTcpClient myTcpClient, MatchType matchType)
 {
     if (MatchType.Client == matchType)
     {
         matchedClientFlag   = true;
         gameSignalingClient = new GameSignalingClient(myTcpClient);
         gameSignalingClient.ReceivedClientReceiveSignalData += (obj) =>
         {
             //   Debug.Log("ClientReceived:" + Enum.GetName(typeof(BattleResult), obj.battleResult));
             //   Debug.Log("ClientReceived:" + Enum.GetName(typeof(CommandKind), obj.commandData.kind));
         };
     }
     else
     {
         matchedHostFlag   = true;
         gameSignalingHost = new GameSignalingHost(myTcpClient, StageKind.Stage1);
         gameSignalingHost.ReceivedHostReceiveSignalData += (obj) =>
         {
             //  Debug.Log("HostReceived:" + Enum.GetName(typeof(CommandKind), obj.clientCommandData.kind));
         };
     }
 }
예제 #23
0
        void Awake()
        {
            var myTcpClient1 = new MyTcpClient("localhost", 3000);
            var myTcpClient2 = new MyTcpClient("localhost", 3000);

            myTcpClient1.Connect();
            myTcpClient2.Connect();

            matchingServer1 = new MatchingClient(myTcpClient1, data =>
            {
                if (data.MatchingDataType == MatchingDataType.MatchedData)
                {
                    if (data.MatchType == MatchType.Host)
                    {
                        CreateGameSignaling(myTcpClient1, data.MatchType.Value);
                    }
                }
                else if (data.MatchingDataType == MatchingDataType.StageDeterminedData)
                {
                    CreateGameSignaling(myTcpClient1, MatchType.Client);
                }
            });
            matchingServer2 = new MatchingClient(myTcpClient2, data =>
            {
                if (data.MatchingDataType == MatchingDataType.MatchedData)
                {
                    if (data.MatchType == MatchType.Host)
                    {
                        CreateGameSignaling(myTcpClient2, data.MatchType.Value);
                    }
                }
                else if (data.MatchingDataType == MatchingDataType.StageDeterminedData)
                {
                    CreateGameSignaling(myTcpClient2, MatchType.Client);
                }
            });
        }
예제 #24
0
        public string SwitchServer(string ip, string port)
        {
            string reply = String.Empty;

            if (String.IsNullOrEmpty(ip) || String.IsNullOrEmpty(port))
            {
                reply = "Invalid IP or Port inserted";
                ThrowNewError(reply);
                return(reply);
            }
            NetworkStream stream = MyTcpClient.InitializeConnection(ip, port);

            if (stream == null)
            {
                reply = "Could not connect to the given IP and Port";
                ThrowNewError(reply);
                return(reply);
            }
            else
            {
                if (!_commandsQueueThread.IsAlive)
                {
                    _commandsQueueThread.Start();
                }

                if (MyTcpClient.ThreadAlreadyRunning)
                {
                    MyTcpClient.KillClient();
                }
                MyTcpClient.M.WaitOne();
                Thread clientThread = new Thread(() => MyTcpClient.CreateAndRunClient(stream));
                clientThread.Start();
                MyTcpClient.ThreadAlreadyRunning = true;
                reply = "Connected succefully to the new server";
            }
            return(reply);
        }
예제 #25
0
 /// <summary>
 /// Instantiates class
 /// </summary>
 /// <param name="Server">The server to connect to</param>
 /// <param name="Port">The port to connect on</param>
 internal NntpClient(string Server, int Port)
 {
     socket         = new MyTcpClient(Server, Port);
     socket.NoDelay = true;
     connectResp    = GetData(false);
 }
예제 #26
0
 public Stream Connect(IBrokerInfo broker)
 {
     _tcpClient = new MyTcpClient(broker.Host, broker.Port);
     return(_tcpClient.GetStream());
 }
예제 #27
0
 public GameSignalingClient(MyTcpClient myTcpClient)
 {
     this.myTcpClient = myTcpClient;
 }
예제 #28
0
        public static void CreatePerson(string firstname, string lastname, string birthday, MyTcpClient currentClient)
        {
            Person p = new Person {
                FirstName = firstname, LastName = lastname, Birthday = DateTime.Parse(birthday)
            };

            SendMessage(JsonConvert.SerializeObject(p), currentClient);
        }
예제 #29
0
        private void openConnection()
        {
            String api_addr = LE_API;

            try
            {
                this.socket = new MyTcpClient(LE_API, Ssl);

                String header = String.Format("PUT /{0}/hosts/{1}/?realtime=1 HTTP/1.1\r\n\r\n",this.SubstituteAppSetting(CONFIG_KEY), this.SubstituteAppSetting(CONFIG_LOCATION));
                this.socket.Write(ASCII.GetBytes(header), 0, header.Length);
            }
            catch
            {
                throw new IOException();
            }
        }
예제 #30
0
 public static void ExitProgram()
 {
     MyTcpClient.KillClient();
 }
예제 #31
0
 private static string SendData(byte[] bits)
 {
     return(MyTcpClient.Connect("127.0.0.1", bits));
 }
 public MatchingClient(MyTcpClient myTcpClient, Action <MatchingData> callback)
 {
     this.myTcpClient     = myTcpClient;
     MatchingDataObserver = Observer.Create(callback);
 }
 public ClientNetworkManager()
 {
     _tcp        = new MyTcpClient(_BUFFER_SIZE, _BUFFER_SIZE);
     _sendStream = new MemoryStream();
 }
예제 #34
0
 public Stream Connect(IBrokerInfo broker)
 {
    _tcpClient = new MyTcpClient(broker.Host, broker.Port);
    return _tcpClient.GetStream();
 }