コード例 #1
0
 private void button2_Click(object sender, EventArgs e)
 {
     try
     {
         if (_ClientRdet == null)
         {
             _ClientRdet = new ClientSocket(_logClient);
         }
         //this.lbcPackage1.Items.Add("Connect 127.0.0.1:5000 ...");
         _ClientRdet.Connect(this.tbServerIP.Text, Convert.ToInt32(this.tbServerPort.Text));
         if (_ClientRdet.IsConnected)
         {
             //this.lbcPackage1.Items.Add("Connect 127.0.0.1:5000 Success!");
             MessageBox.Show("Connect " + this.tbServerIP.Text + ":" + tbPort.Text + " Success!");
         }
         else
         {
             //this.lbcPackage1.Items.Add("Connect 127.0.0.1:5000 failure!");
             MessageBox.Show("Connect " + this.tbServerIP.Text + ":" + tbPort.Text + " Failure!");
         }
     }
     finally
     {
         _ClientRdet.DisConnect(false);
     }
 }
コード例 #2
0
        public async Task Connect(AddressType Address,
                                  Func <IAsyncOprations, Task> Requestor)
        {
            await ClientSocket.Connect(Address);

            using (var rq = new AsyncOprations <AddressType>(ClientSocket, false))
            {
                await Requestor(rq);
            }
#if DEBUG
            ClientSocket.AddDebugInfo("end.");
#endif
            await ClientSocket.Disconncet();
        }
コード例 #3
0
        private void Btn_cont_Click(object sender, RoutedEventArgs e)
        {
            if (btn_cont.IsChecked == true)
            {
                clientSocket = new ClientSocket("127.0.0.1", 10001);

                clientSocket.OnServerClose -= ClientSocket_OnServerClose;
                clientSocket.OnServerClose += ClientSocket_OnServerClose;
                clientSocket.ReceiveData   -= ClientSocket_ReceiveData;
                clientSocket.ReceiveData   += ClientSocket_ReceiveData;

                if (clientSocket.Connect())
                {
                    MSG("服务器已经连接");
                }
                else
                {
                    MSG("服务器连接失败");
                    btn_cont.IsChecked = false;
                }
            }
            else
            {
                clientSocket.Disconnect();
                MSG("服务器已经断开连接");
            }
        }
コード例 #4
0
ファイル: Sock.cs プロジェクト: 2010phenix/RemoteDesktop-1
        public void Connect(IPAddress ip, int port)
        {
            try
            {
                ClientSocket.Connect(new IPEndPoint(ip, 100));
            }
            catch (SocketException sockEx)
            {
                if (string.Equals(sockEx.Message, "No connection could be made because the target machine actively refused it"))
                {
                    if (OnConnect != null)
                    {
                        OnConnect(false);
                    }
                }
            }

            if (ClientSocket.Connected)
            {
                var sock = new Sock.Server(ClientSocket, DataBuffer.Length);
                sock.ServerSocket.BeginReceive(DataBuffer, 0, DataBuffer.Length, SocketFlags.None, new AsyncCallback(OnReceive), sock);
            }

            if (OnConnect != null)
            {
                OnConnect(ClientSocket.Connected);
            }
        }
コード例 #5
0
ファイル: Program.cs プロジェクト: liujunjie612/ScorpioNet
        static void Main(string[] args)
        {
            logger.SetLog(new Log());
            ServerSocket server = new ServerSocket(new ServerFactory());

            server.Listen(9999);
            ClientSocket client = new ClientSocket(new ClientFactory());

            client.Connect("localhost", 9999);
            while (true)
            {
                string str = Console.ReadLine();
                if (str.StartsWith("file "))
                {
                    ClientConnection.GetInstance().SendFile(str.Replace("file ", ""));
                }
                else if (str.StartsWith("cmd "))
                {
                    ClientConnection.GetInstance().Send(3, 0, Encoding.UTF8.GetBytes(str.Replace("cmd ", "")));
                }
                else if (str == "exit")
                {
                    ClientConnection.GetInstance().Disconnect();
                    break;
                }
                else
                {
                    ClientConnection.GetInstance().Send(100, 9999, Encoding.UTF8.GetBytes(str));
                }
            }
            Console.ReadKey();
        }
コード例 #6
0
    private void ConnectToGameServer()
    {
        if (caseomaticUsername == "")
        {
            Debug.Log("You cannot connect to the game server without a specified username.");
            return;
        }
        if (gameDataServerConnectionMode == GameDataServerConnectionMode.Connected)
        {
            Debug.Log("You cannot connect to the game server if you already are connected.");
            return;
        }

        try
        {
            isLoading = true;
            gameDataServerEndPoint = new IPEndPoint(IPAddress.Loopback, 42001); // Find out the game server endpoint

            socket = new ClientSocket(gameDataServerClientPort);
            socket.Connect(gameDataServerEndPoint);
            progress += 25;

            SendGameServerMessage("login", caseomaticUsername, projectBronzeAgeUserId);
            progress += 25;
        }
        catch (Exception ex)
        {
            Debug.LogException(ex);
            gameDataServerConnectionMode = GameDataServerConnectionMode.Aborted;
            loadErrorOccured             = true;
        }
    }
コード例 #7
0
ファイル: SocketNetProxy.cs プロジェクト: illden/Scut
 public override void CheckConnect()
 {
     if (!_client.Connected)
     {
         _client.Connect();
     }
 }
コード例 #8
0
        public void Go()
        {
            client              = new ClientSocket();
            client.OnConnected += new Sockets.OnConnectDelegate(OnConnected);
            client.OnReceived  += new Sockets.OnReceiveDelegate(OnReceived);

            client.AddReceiveEventHandler(typeof(EchoCommand), OnEcho);
            client.AddReceiveEventHandler(typeof(WhatTimeIsItCommand), OnWhatTimeIsIt);

            // use the xml buffer codec for this client endpoint.
            client.BufferCodec = new XmlBufferCodec();

            // NOTE that this will happen several times, since the Server and Client testing
            // is done in the same main running process, as such, multiple scanning will
            // happen, in a real-life program, this will not happen, since each process is
            // self contained, and should theoritically handle its own SET.
            client.BufferCodec.ScanForIdentity(
                "Pivotal.Core.NET",
                "^Pivotal.Core.NET.*Command$"
                );
            client.BufferCodec.ScanForIdentity(
                "Pivotal.Core.NET.TestServer",
                "^Pivotal.Core.NET.*Command$"
                );

            client.Connect("127.0.0.1", 8090);
        }
コード例 #9
0
    public void Connect(string ip, int port)
    {
        Debug.Assert(clientSocket == null);

        clientSocket = new ClientSocket();
        clientSocket.Connect(ip, port);
    }
コード例 #10
0
 private void connectionTimer_Tick(object sender, EventArgs e)
 {
     //TcpClient tcpClient = new TcpClient();
     //try
     //{
     //tcpClient.Connect(ipAddress, port);
     //Console.WriteLine("Server online");
     if (!ClientSocket._socket.Connected)
     {
         try
         {
             ClientSocket.Connect(ipAddress, port);
             Console.WriteLine("Spojen!");
             //connectionTimer.Stop();
         }
         catch
         {
             Console.WriteLine("Nije spojen!");
         }
     }
     //}
     //catch (Exception)
     //{
     //Console.WriteLine("Server online");
     //}
 }
コード例 #11
0
        private async void Connect(object sender, EventArgs eventArgs)
        {
            await clsock.Connect();

            textbox_server.Text = "IP сервера: 192.168.1.35";
            btn_connect.Enabled = false;
        }
コード例 #12
0
ファイル: SocketRemotingClient.cs プロジェクト: wh-ess/ess
        private void ReconnectServer()
        {
            if (_clientSocket.IsConnected)
            {
                return;
            }

            var success = false;

            try
            {
                _clientSocket.Shutdown();
                _clientSocket = new ClientSocket(new RemotingClientSocketEventListener(this));
                _clientSocket.Connect(_address, _port);
                _clientSocket.Start(ReceiveMessage);
                success = true;
            }
            catch
            {
            }

            if (success)
            {
                OnServerReconnected(_clientSocket.SocketInfo);
                StopReconnectServerTask();
            }
        }
コード例 #13
0
        public Form1()
        {
            InitializeComponent();

            _mySock               = new ClientSocket("192.168.10.212", 11111);
            _mySock.Connected    += MySockOnConnected;
            _mySock.Disconnected += MySockOnDisconnected;
            _mySock.DataReceived += MySockOnDataReceived;
            _mySock.Connect();

            JObject jsonObject = JObject.FromObject(
                new
            {
                Cookie     = FTNN.getCookie(),
                EnvType    = "0",
                StockCode  = "",
                StockType  = "",
                PLRatioMin = "",
                PLRatioMax = ""
            });


            Program.ftnn.request(FTNN.protocol.港股查询持仓列表, jsonObject,
                                 (JObject a) => {
                WriteToBox(a.ToString());
            });
        }
コード例 #14
0
    /// <summary>
    /// 连接网络
    /// </summary>
    /// <param name="address">网络地址</param>
    public void Connect(string address)
    {
        // 防止重入

        if (_socket != null)
        {
            return;
        }

        _socket = new ClientSocket();

        _socket.EventRecvPacket += OnReceiveSocketMessage;

        _socket.EventConnected += delegate()
        {
            PostMessage(_peerConnectedMsgID, null);
        };

        _socket.EventClosed += delegate(NetworkReason reason)
        {
            PostMessage(_peerClosedMsgID, null);
        };

        Address = address;
        _socket.Connect(address);
    }
コード例 #15
0
        private void LoopConnect()
        {
            int attempts = 0;

            while (!ClientSocket.Connected && attempts < 10)
            {
                attempts++;
                try
                {
                    ClientSocket.Connect(IPAddress.Loopback, 219);
                }
                catch (Exception e)
                {
                    Log("Error Occured: " + e.GetType().ToString() + ": " + e.Message);
                    Log("Connection Attempt: " + attempts);
                }
                Update();
            }
            if (ShownConnectMessage)
            {
                return;
            }
            if (ClientSocket.Connected && !ShownConnectMessage)
            {
                Log("Connected!");
                ShownConnectMessage = true;
            }
            else
            {
                Log("Could not connect to server!\nExiting! (Servers may be down, your firewall is blocking it, or your ISP is blocking the server!)", true);
                Application.Exit();
            }
        }
コード例 #16
0
ファイル: NCUIForm.cs プロジェクト: Chloee524/New_CUI
        private void button_Connect_Click(object sender, EventArgs e)
        {
            bool isSuccess = false;

            if (string.IsNullOrEmpty(ipAddressControl1.Text) || string.IsNullOrEmpty(textBox_Port.Text))
            {
                toolStripStatusLabel.Text = "IP 주소 및 Port 번호를 확인 해 주세요.";
            }
            else
            {
                isSuccess = _client.Connect(ipAddressControl1.Text, int.Parse(textBox_Port.Text));

                if (isSuccess)
                {
                    button_Connect.Enabled    = false;
                    button_Discon.Enabled     = true;
                    button_Send.Enabled       = true;
                    button_SymbolSend.Enabled = true;
                    button_INIT.Enabled       = true;
                    button_1.Enabled          = true;
                    button_2.Enabled          = true;
                    button_3.Enabled          = true;
                    button_4.Enabled          = true;
                    button_5.Enabled          = true;
                    toolStripStatusLabel.Text = "IP 주소 : " + ipAddressControl1.Text +
                                                " 포트 번호 : " + textBox_Port.Text + "로 연결 완료";
                }
            }
        }
コード例 #17
0
 private void button1_Click(object sender, EventArgs e)
 {
     _mySock               = new ClientSocket(textBox1.Text, 11111);
     _mySock.Connected    += MySockOnConnected;
     _mySock.Disconnected += MySockOnDisconnected;
     _mySock.DataReceived += MySockOnDataReceived;
     _mySock.Connect();
 }
コード例 #18
0
ファイル: ClientServer.cs プロジェクト: zredb/netmq
        public void AsyncEnumerable()
        {
            using var server = new ServerSocket();
            int port = server.BindRandomPort("tcp://*");

            using var client = new ClientSocket();
            client.Connect($"tcp://127.0.0.1:{port}");

            int totalCount = 0;

            var t1 = Task.Run(async() =>
            {
                int count = 0;

                await foreach (var(_, msg) in server.ReceiveStringAsyncEnumerable())
                {
                    count++;
                    Interlocked.Increment(ref totalCount);

                    if (msg == "1")
                    {
                        m_testOutputHelper.WriteLine($"T1 read {count} messages");
                        return;
                    }
                }
            });

            var t2 = Task.Run(async() => {
                int count = 0;

                await foreach (var(_, msg) in server.ReceiveStringAsyncEnumerable())
                {
                    count++;
                    Interlocked.Increment(ref totalCount);

                    if (msg == "1")
                    {
                        m_testOutputHelper.WriteLine($"T2 read {count} messages");
                        return;
                    }
                }
            });

            for (int i = 0; i < 15000; i++)
            {
                client.Send("0");
            }

            // Send the end message to both of the threads
            client.Send("1");
            client.Send("1");

            t1.Wait();
            t2.Wait();

            Assert.Equal(15002, totalCount);
        }
コード例 #19
0
        public static void StartUp(string Ip, int Port)
        {
            ClientSocket.Connect(IPAddress.Parse(Ip), Port);
            SecureClientSocket.Connect(IPAddress.Parse(Ip), Port);

            SNetServerProcess.StartProcess();
            SNetPlayerConnector.Connect();

            Debug.Log("Client running!");
        }
コード例 #20
0
        public void Login(object obj)
        {
            ClientSocket sock = new ClientSocket();

            sock.Connect("45.63.1.88", 1060);
            Thread.Sleep(100);
            MyMessage AuthRequest = new MyMessage(UserName + "\r\n" + PasswordHandler(), 10);

            sock.Send(AuthRequest.Data);
        }
コード例 #21
0
        internal WindowManager(MainWindow mainwnd)
        {
            Instance   = this;
            mainWindow = mainwnd;

            string clientPort     = Interaction.InputBox("Client port", "Case-o-Matic Client");
            string serverEndPoint = Interaction.InputBox("Server-endpoint", "Case-o-Matic Client");

            clientSocket = new ClientSocket(int.Parse(clientPort));
            clientSocket.Connect(new IPEndPoint(IPAddress.Parse(serverEndPoint.Split(':')[0]), int.Parse(serverEndPoint.Split(':')[1])));
        }
コード例 #22
0
ファイル: SocketNetProxy.cs プロジェクト: illden/Scut
        public SocketNetProxy(string host, int port)
        {
            var ipAddress = Dns.GetHostAddresses(host).First();

            _address = new IPEndPoint(ipAddress, port);
            var setting = new ClientSocketSettings(BufferSize, _address);

            _client = new ClientSocket(setting);
            _client.DataReceived += DoReceived;
            _client.Connect();
        }
コード例 #23
0
 public void OnlineClicked()
 {
     canGameStart = false;
     Loading.SetActive(true);
     isOnlineClicked = true;
     ClientSocket.Connect();
     //if (ClientSocket.connnetionSuccess) {
     //    OnlineOrOffline.SetActive(false);
     //    LoginOrRegist.SetActive(true);
     //}
 }
コード例 #24
0
        public void TestEventHandlers(string before, string after)
        {
            string expectedAnswer = "Name: Igor Eliseev, Message: " + after;
            string actualAnswer   = null;
            bool   wait           = true;
            int    numMessages    = 0;

            ServerSocket server = new ServerSocket(8080, 6);

            void ServerRun()
            {
                try
                {
                    server.WaitClientConnection();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
                Message msg = server.Receive();

                wait = false;
                server.Send(msg);
                numMessages = server.GetAllMessages().Count;
            }

            Thread threadServer = new Thread(new ThreadStart(ServerRun));

            threadServer.Start();

            Client       client       = new Client("Igor Eliseev", null);
            ClientSocket clientSocket = new ClientSocket(client, "127.0.0.1", 8080);

            clientSocket.Connect();
            Message message = new Message(before, client);

            clientSocket.Send(message);
            while (wait)
            {
                ;
            }

            actualAnswer = clientSocket.Receive();
            clientSocket.Close();

            Thread.Sleep(1000);

            Assert.NotNull(expectedAnswer);
            Assert.NotNull(actualAnswer);
            Assert.AreEqual(expectedAnswer, actualAnswer);
            Assert.AreEqual(1, numMessages);

            threadServer.Abort();
        }
コード例 #25
0
ファイル: SocketNetProxy.cs プロジェクト: zhangxiangbing/Scut
 public override void CheckConnect()
 {
     if (!_isConnected)
     {
         _client = new ClientSocket(setting);
         _client.DataReceived += DoReceived;
         _client.Disconnected += DoClosed;
         _client.Connect();
         _isConnected = true;
     }
 }
コード例 #26
0
        private void button2_Click(object sender, EventArgs e)
        {
            this.CreateClientSocket();

            string sServerIP   = tbServerIP.Text;
            int    iServerPort = Convert.ToInt32(tbServerPort.Text);


            _ClientSocket.Connect(sServerIP, iServerPort, _logClient);
            if (_ClientSocket.IsConnected())
            {
                //this.lbcPackage1.Items.Add("Connect 127.0.0.1:5000 Success!");
                MessageBox.Show("Connect " + sServerIP + ":" + iServerPort.ToString() + " Success!");
            }
            else
            {
                //this.lbcPackage1.Items.Add("Connect 127.0.0.1:5000 failure!");
                MessageBox.Show("Connect " + sServerIP + ":" + iServerPort.ToString() + " Failure!");
            }
            _ClientSocket.DisConnect(false);
        }
コード例 #27
0
        public void Connect_InvalidIp()
        {
            var  mySocket          = new ClientSocket("172.16.0.1", 802);
            bool connectEventFired = false;

            mySocket.Connected += args => { connectEventFired = true; };

            mySocket.Connect();

            Assert.IsFalse(mySocket.IsConnected, "Managed to connect to invalid address.");
            Assert.IsFalse(connectEventFired, "The connection event fired.");
        }
コード例 #28
0
        public void Connect_InvalidPort()
        {
            var  mySocket          = new ClientSocket("google.com", 802);
            bool connectEventFired = false;

            mySocket.Connected += args => { connectEventFired = true; };

            mySocket.Connect();

            Assert.IsFalse(mySocket.IsConnected, "Managed to connect to invalid port.");
            Assert.IsFalse(connectEventFired, "The connection event fired.");
        }
コード例 #29
0
ファイル: Program.cs プロジェクト: sysrpl/Codebot.Raspberry
        static void ServerAccept(object sender, SocketAcceptEventArgs e)
        {
            var s = e.Socket;

            Console.WriteLine("Accepted connection from " +
                              IPAddress.Parse(((IPEndPoint)s.RemoteEndPoint).Address.ToString()) +
                              " on port number " + ((IPEndPoint)s.RemoteEndPoint).Port.ToString());
            var client = new ClientSocket(1000);

            client.Receive += ClientReceive;
            client.Connect(s);
        }
コード例 #30
0
    /// <summary>
    /// 连接网络
    /// </summary>
    /// <param name="address">网络地址</param>
    public void Connect(string address)
    {
        // 防止重入

        if (_socket != null)
        {
            return;
        }

        _socket = new ClientSocket();

        _socket.OnRecv += (msgid, stream) =>
        {
            PostStream(msgid, stream);
        };

        _socket.OnConnected += delegate()
        {
            PostStream(MsgID_Connected, null);
        };

        _socket.OnDisconnected += delegate()
        {
            PostStream(MsgID_Disconnected, null);
        };

        _socket.OnError += delegate(NetworkReason reason)
        {
            switch (reason)
            {
            case NetworkReason.ConnectError:
            {
                PostStream(MsgID_ConnectError, null);
            }
            break;

            case NetworkReason.SendError:
            {
                PostStream(MsgID_SendError, null);
            }
            break;

            case NetworkReason.RecvError:
            {
                PostStream(MsgID_RecvError, null);
            }
            break;
            }
        };

        Address = address;
        _socket.Connect(address);
    }
コード例 #31
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="remoteEndPoint"></param>
        /// <param name="route">远端执行方法名</param>
        /// <param name="param">参数</param>
        /// <param name="bufferSize"></param>
        protected void DoRequest(IPEndPoint remoteEndPoint, string param, int bufferSize)
        {
            client = new ClientSocket(new ClientSocketSettings(1024, remoteEndPoint));
            client.Disconnected += DoDisconnected;
            client.DataReceived += DoReceive;
            client.Connect();
            byte[] data = Encoding.UTF8.GetBytes("?d="+param);

            client.PostSend(data, 0, data.Length);
            if (!client.WaitAll(10000))
            {
                DoError("请求超时");
            }
        }
コード例 #32
0
ファイル: BoltSocketTests.cs プロジェクト: byteshadow/bolt
        public void AyncTcpServer()
        {
            ServerSocket serverSocket = new ServerSocket();
            serverSocket.Bind(9900);

            serverSocket.AddMessageHandler<SampleMessage>(SampleMessageHandler);

            // Get host related information.
            IPAddress[] addressList = Dns.GetHostEntry(Environment.MachineName).AddressList;

            // Get endpoint for the listener.
            IPEndPoint localEndPoint = new IPEndPoint(addressList[addressList.Length - 1], 9900);

            long totalTime = 0;
            const int msgs = (int)1e5;
            int msgLength = 0;
            Action action = () =>
                {
                    ClientSocket clientSocket = new ClientSocket();
                    clientSocket.Connect(localEndPoint);

                    Assert.IsTrue(clientSocket.Connected);

                    Stopwatch sw = Stopwatch.StartNew();
                    Serializer serializer = new Serializer();

                    var sample = new SampleMessage { X = 38 };
                    var msg = serializer.Serialize(sample);
                    msgLength = msg.Length;

                    for (int i = 0; i < msgs; i++)
                    {
                        clientSocket.Send(sample);
                    }

                    sw.Stop();

                    Interlocked.Add(ref totalTime, sw.ElapsedMilliseconds);

                    SpinWait.SpinUntil(() => counter == msgs, 2000);

                    //networkStream.Close();
                    clientSocket.Close();
                };

            List<Action> actions = new List<Action>();
            int numOfClients = 1;

            for (int i = 0; i < numOfClients; i++)
            {
                actions.Add(action);
            }

            Stopwatch sw2 = Stopwatch.StartNew();
            Parallel.Invoke(actions.ToArray());

            if (!Debugger.IsAttached)
                SpinWait.SpinUntil(() => counter == msgs * numOfClients, 2000);
            else
            {
                SpinWait.SpinUntil(() => counter == msgs * numOfClients, 60000);
            }

            sw2.Stop();

            Console.WriteLine("Num Of Msgs: {0:###,###}", counter);
            Console.WriteLine("Average for each client {0}ms", totalTime / actions.Count);
            Console.WriteLine("Average Speed for each client: {0:###,###}msgs/s", (msgs / (totalTime / actions.Count)) * 1000);
            Console.WriteLine("Total time: {0}ms", sw2.ElapsedMilliseconds);
            Console.WriteLine("Msgs/s {0:###,###}", (counter / sw2.ElapsedMilliseconds) * 1000);
            Console.WriteLine("Msg length {0}bytes", msgLength);
            Assert.AreEqual(msgs * numOfClients, counter, "Not all msgs received");
        }