コード例 #1
0
ファイル: SocketServer.cs プロジェクト: roe0901/redishelper
        private void HandleClientComm(object client)
        {
            Socket socketClient = (Socket)client;

            socketClient.NoDelay = true;

            LingerOption lingerOption = new LingerOption(true, 3);

            socketClient.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, lingerOption);

            string request = string.Empty;

            try
            {
                byte[] headBuffer = new byte[4];
                // 读取头信息 接受的长度
                socketClient.Receive(headBuffer, 4, SocketFlags.None);
                // 需要接受的长度
                int needRecvLength = BitConverter.ToInt32(headBuffer, 0);

                if (needRecvLength != 0)
                {
                    // 未接受的长度
                    int notRecvLength = needRecvLength;

                    // 分配空间
                    byte[] readBuffer = new byte[needRecvLength + headLength];

                    // 接受信息
                    do
                    {
                        // 已经接受的长度
                        int hasRecv = socketClient.Receive(readBuffer, headLength + needRecvLength - notRecvLength, notRecvLength, SocketFlags.None);
                        notRecvLength -= hasRecv;
                    } while (notRecvLength != 0);

                    request = Encoding.UTF8.GetString(readBuffer, headLength, needRecvLength);
                }


                StringBuilder response = new StringBuilder(request);
                Console.WriteLine("收到客户端消息:" + response);
                if (socketClient.Connected)
                {
                    string sendString = string.Format("还你_{0}456", response.ToString());

                    // 发送字符串
                    byte[] contentByte = Encoding.UTF8.GetBytes(sendString);
                    byte[] headBytes   = BitConverter.GetBytes(contentByte.Length);

                    byte[] sendByte = new byte[headBytes.Length + contentByte.Length];

                    headBytes.CopyTo(sendByte, 0);
                    contentByte.CopyTo(sendByte, headLength);

                    int needSendLength = sendByte.Length;

                    do
                    {
                        int nSend = socketClient.Send(sendByte, sendByte.Length - needSendLength, needSendLength, SocketFlags.None);
                        needSendLength -= nSend;
                    } while (needSendLength != 0);

                    Console.WriteLine("消息回复完成:" + sendString);
                }
            }
            #region 全局错误处理
            catch (SocketException ex)
            {
                if (socketClient.Connected)
                {
                    socketClient.Shutdown(SocketShutdown.Both);
                    socketClient.Close();
                }
            }
            catch (Exception ex)
            {
                // 写错误日志
                //EventLogger.LogError(ex.Message);

                // 发错误邮件
                if (ex.InnerException != null)
                {
                    ex = ex.InnerException;
                }

                string mailBody = string.Format("用户输入:{0}{1}{0}错误信息:{0}{2}{0}堆栈信息:{0}{3}{0}", "\r\n", request, ex.Message, ex.StackTrace);
            }
            #endregion
        }
コード例 #2
0
        private void AcceptSocketCallback(IAsyncResult ar)
        {
            Socket socket = null;
            TcpServerSocketHandler streamManager = null;
            bool flag = true;

            try
            {
                if (this._tcpListener.IsListening)
                {
                    this._tcpListener.BeginAcceptSocket(this._acceptSocketCallback, null);
                }
                socket = this._tcpListener.EndAcceptSocket(ar);
                if (socket == null)
                {
                    throw new RemotingException(string.Format(CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Socket_Accept"), new object[] { Marshal.GetLastWin32Error().ToString(CultureInfo.CurrentCulture) }));
                }
                if ((this._authorizeRemotingConnection != null) && !this._authorizeRemotingConnection.IsConnectingEndPointAuthorized(socket.RemoteEndPoint))
                {
                    throw new RemotingException(CoreChannel.GetResourceString("Remoting_Tcp_ServerAuthorizationEndpointFailed"));
                }
                socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.Debug, 1);
                socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1);
                LingerOption optionValue = new LingerOption(true, 3);
                socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, optionValue);
                Stream stream = new SocketStream(socket);
                streamManager = new TcpServerSocketHandler(socket, CoreChannel.RequestQueue, stream);
                WindowsIdentity identity = null;
                flag = false;
                if (this._secure)
                {
                    identity      = this.Authenticate(ref stream, streamManager);
                    streamManager = new TcpServerSocketHandler(socket, CoreChannel.RequestQueue, stream);
                    if ((this._authorizeRemotingConnection != null) && !this._authorizeRemotingConnection.IsConnectingIdentityAuthorized(identity))
                    {
                        throw new RemotingException(CoreChannel.GetResourceString("Remoting_Tcp_ServerAuthorizationIdentityFailed"));
                    }
                }
                streamManager.ImpersonationIdentity = identity;
                streamManager.DataArrivedCallback   = new WaitCallback(this._transportSink.ServiceRequest);
                streamManager.BeginReadMessage();
            }
            catch (Exception exception)
            {
                try
                {
                    if (streamManager != null)
                    {
                        streamManager.SendErrorResponse(exception, false);
                    }
                    if (socket != null)
                    {
                        if (flag)
                        {
                            socket.Close(0);
                        }
                        else
                        {
                            socket.Close();
                        }
                    }
                }
                catch (Exception)
                {
                }
                if (this._bListening)
                {
                    SocketException exception3 = exception as SocketException;
                }
            }
        }
コード例 #3
0
        protected static void tcpListen()
        {
            try
            {
                //IPAddress ipAddress = Dns.Resolve("localhost").AddressList[0];
                //listener = new TcpListener(ipAddress, ServerTcpClient.odbTcpPort);
                //listener = new TcpListener(IPAddress.IPv6Any, ServerTcpClient.odbTcpPort);
                listener = new TcpListener(IPAddress.Any, SessionBase.s_serverTcpIpPortNumber);
                Socket       s            = listener.Server;
                LingerOption lingerOption = new LingerOption(true, 0);
                s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, lingerOption);
                s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
                s.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, 1);
                listener.Start();
            }
            catch (System.Exception e)
            {
                ServerTcpClient.s_odbServerLog.WriteEntry(e.ToString());
            }

            try
            {
                while (!ServerTcpClient.ShutDown)
                {
                    ServerTcpClient.s_acceptDone.Reset();
#if NET_COREx
                    //listener?.AcceptSocketAsync().Wait();
                    ServerTcpClient.AcceptTcpClient(listener);
#else
                    listener?.BeginAcceptTcpClient(new AsyncCallback(ServerTcpClient.AcceptTcpClient), listener);
#endif

                    ServerTcpClient.s_acceptDone.WaitOne();
                }
            }
            catch (SocketException e)
            {
#if !NET_COREx
                if (e.ErrorCode != 10054) // client closed socket
#endif
                {
                    ServerTcpClient.s_odbServerLog.WriteEntry(e.ToString());
                }
            }
            catch (System.Exception e)
            {
                ServerTcpClient.s_odbServerLog.WriteEntry(e.ToString());
            }
            finally
            {
                listener.Stop();
            }

            if (!stopService)
            {
                try
                {
                    listener?.Stop();
                    Environment.Exit(0);
                }
                catch (System.Exception e)
                {
                    ServerTcpClient.s_odbServerLog.WriteEntry(e.ToString());
                }
            }
        }
コード例 #4
0
    public void PlaymodeCallback()
    {
        if ( EditorApplication.isPlayingOrWillChangePlaymode == false )
        {

            if ( currentConnection != null )
            {

                currentConnection.Socket.Close ();
                currentConnection = null;
            }

            if ( listenSocket != null )
            {

                LingerOption lingerOption = new LingerOption ( false, 0 );
                listenSocket.SetSocketOption ( SocketOptionLevel.Socket, SocketOptionName.Linger, lingerOption );
                listenSocket.Close ();
                listenSocket = null;
            }
        }
    }
コード例 #5
0
    public bool ShutdownHost()
    {
        chatMessages = new List<String> ();

        opponent.name = null;
        opponent.cards.Clear ();

        info = false;
        infoString = null;

        hosting = false;
        connectionType = ConnectionType.None;

        if ( currentConnection != null )
        {

            currentConnection.Socket.Close ();
            currentConnection = null;
        }

        LingerOption lingerOption = new LingerOption ( false, 0 );
        listenSocket.SetSocketOption ( SocketOptionLevel.Socket, SocketOptionName.Linger, lingerOption );
        listenSocket.Close ();
        listenSocket = null;

        debugLog.ReceiveMessage ( "\tConnection Type Set to None" );

        return true;
    }
コード例 #6
0
 public static ILingerOption ToInterface([CanBeNull] this LingerOption option)
 {
     return((option == null) ? null : new LingerOptionAdapter(option));
 }
コード例 #7
0
        void CloseLingerX(bool closeStream, bool closeClient)
        {
            LingerOption lingerOption = new LingerOption(true, Test_LingerTimeSeconds);

            CloseX(closeStream, closeClient, lingerOption);
        }
コード例 #8
0
ファイル: tcpserverchannel.cs プロジェクト: ydunk/masters
        } // StopListening

        //
        // end of IChannelReceiver implementation
        //


        //
        // Server helpers
        //

        // Thread for listening
        void Listen()
        {
            bool bOkToListen = false;

            try
            {
                _tcpListener.Start();
                bOkToListen = true;
            }
            catch (Exception e)
            {
                _startListeningException = e;
            }

            _waitForStartListening.Set(); // allow main thread to continue now that we have tried to start the socket

            InternalRemotingServices.RemotingTrace("Waiting to Accept the Socket on Port: " + _port);

            //
            // Wait for an incoming socket
            //
            Socket socket;

            while (bOkToListen)
            {
                InternalRemotingServices.RemotingTrace("TCPChannel::Listen - tcpListen.Pending() == true");

                try
                {
                    socket = _tcpListener.AcceptSocket();

                    if (socket == null)
                    {
                        throw new RemotingException(
                                  String.Format(
                                      CoreChannel.GetResourceString("Remoting_Socket_Accept"),
                                      Marshal.GetLastWin32Error().ToString()));
                    }

                    // disable nagle delay
                    socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, 1);

                    // set linger option
                    LingerOption lingerOption = new LingerOption(true, 3);
                    socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, lingerOption);

                    TcpServerSocketHandler streamManager = new TcpServerSocketHandler(socket, CoreChannel.RequestQueue);
                    streamManager.DataArrivedCallback = new WaitCallback(_transportSink.ServiceRequest);
                    streamManager.BeginReadMessage();
                }
                catch (Exception e)
                {
                    if (!_bListening)
                    {
                        // We called Stop() on the tcp listener, so gracefully exit.
                        bOkToListen = false;
                    }
                    else
                    {
                        // we want the exception to show up as unhandled since this
                        //   is an unexpected failure.
                        if (!(e is SocketException))
                        {
                            //throw;
                        }
                    }
                }
            }
        }
コード例 #9
0
ファイル: CableCloud.cs プロジェクト: pawerrs/TSST-Project
        /// <summary>
        /// Funkcja sluży do
        /// Zwraca socket
        /// </summary>
        /// <param name="adresIPListener">Parametrem jest adres IP na ktorym nasluchujemy  </param>
        ///  /// <param name="key">Parametrem jest warotsc klucza wlasnosci z pliku config  </param>
        private static Socket ListenAsync(string adresIPListener, string key, CancellationToken cancellationToken = default(CancellationToken))
        {
            Socket    socketClient = null;
            Socket    listener     = null;
            IPAddress ipAddress    =
                ipAddress = IPAddress.Parse(adresIPListener);
            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);


            cancellationToken.ThrowIfCancellationRequested();

            try
            {
                byte[] bytes = new Byte[1024];

                // Create a TCP/IP socket.
                listener = new Socket(ipAddress.AddressFamily,
                                      SocketType.Stream, ProtocolType.Tcp);

                if (!listener.IsBound)
                {
                    //zabindowanie na sokecie punktu koncowego
                    listener.Bind(localEndPoint);
                    listener.Listen(100);
                }

                cancellationToken.ThrowIfCancellationRequested();

                //Nasluchujemy bez przerwy
                while (Last)
                {
                    if (Listening)
                    {
                        //oczekiwanie na polaczenie
                        socketClient = listener.Accept();
                        //dodanie do listy sluchaczy po przez delegata
                        sd(socketClient);
                        Socket send = null;

                        //Znajac dlugosc slowa "Listener" pobieram z calej nazwy klucza tylko index, ktory wykorzystam aby dopasowac do socketu OUT
                        string str = key.Substring(8, key.Length - 8);

                        //Sklejenie czesci wspolnej klucza dla socketu OUT oraz indeksu
                        string settingsString = "Sending" + str;

                        //Dodanie socketu do listy socketow OUT
                        socketSendingList.Add(sS.ConnectToEndPoint(OperationConfiguration.getSetting(settingsString, readSettings)));
                        Listening = false;
                        LingerOption myOpts = new LingerOption(true, 1);
                        socketClient.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, myOpts);
                        socketClient.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, false);
                        socketClient.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

                        Console.WriteLine("Polaczenie na  " + takingAddresListenerSocket(socketClient));


                        string fromAndFrequency;


                        //Oczekiwanie w petli na przyjscie danych
                        while (true)
                        {
                            //Odebranie tablicy bajtow na obslugiwanym w watku sluchaczu

                            msg = sl.ProcessRecivedBytes(socketClient);

                            // Package.extractHowManyPackages(msg);
                            // listByte.Add(msg);

                            //Wykonuje jezeli nadal zestawione jest polaczenie
                            if (socketClient.Connected)
                            {
                                stateReceivedMessage(msg, socketClient);
                                //Uzyskanie czestotliwosci zawartej w naglowku- potrzebna do okreslenia ktorym laczem idzie wiadomosc
                                frequency        = Package.extractPortNumber(msg);
                                fromAndFrequency = takingAddresListenerSocket(socketClient) + " " + frequency;

                                //wyznaczenie socketu przez ktory wyslana zostanie wiadomosc
                                send = sendingThroughSocket(fromAndFrequency);
                                stateSendingMessage(msg, send, fromAndFrequency);
                                //wyslanei tablicy bajtow
                                sS.SendingPackageBytes(send, msg);
                            }
                            else
                            {
                                //Jezeli host zerwie polaczneie to usuwamy go z listy przetrzymywanych socketow, aby rozpoczac proces nowego polaczenia
                                int numberRemove = socketListenerList.IndexOf(socketClient);
                                socketListenerList.RemoveAt(numberRemove);
                                socketSendingList.RemoveAt(numberRemove);
                                break;
                            }
                        }
                        Listening = true;
                    }
                }
            }
            catch (SocketException se)
            {
                Console.WriteLine($"Socket Exception: {se}");
            }
            finally
            {
                // StopListening();
            }
            if (socketClient == null)
            {
                return(new Socket(ipAddress.AddressFamily,
                                  SocketType.Stream, ProtocolType.Tcp));
            }

            return(socketClient);
        }
コード例 #10
0
 private protected static void ConfigureSocket(Socket socket, LingerOption linger, byte ttl)
 {
     socket.NoDelay = true;
     socket.Ttl     = ttl;
     socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, linger);
 }
コード例 #11
0
ファイル: SocketListener.cs プロジェクト: qiuhoude/mu_server
        private void ProcessAccept(SocketAsyncEventArgs e)
        {
            TMSKSocket s = new TMSKSocket(e.AcceptSocket);

            s.SetAcceptIp();
            bool disableConnect = false;
            bool?inIpWriteList  = null;

            if (this.EnabledIPListFilter)
            {
                lock (this.IPWhiteList)
                {
                    if (this.EnabledIPListFilter && s != null && null != s.RemoteEndPoint)
                    {
                        IPEndPoint remoteIPEndPoint = s.RemoteEndPoint as IPEndPoint;
                        if (remoteIPEndPoint != null && null != remoteIPEndPoint.Address)
                        {
                            string remoteIP = remoteIPEndPoint.Address.ToString();
                            if (!string.IsNullOrEmpty(remoteIP) && !this.IPWhiteList.ContainsKey(remoteIP))
                            {
                                LogManager.WriteLog(LogTypes.Error, string.Format("新远程连接: {0}, 但是客户端IP处于IP过滤中:{1}", s.RemoteEndPoint, this.ConnectedSocketsCount), null, true);
                                inIpWriteList = new bool?(false);
                            }
                            else
                            {
                                inIpWriteList = new bool?(true);
                            }
                        }
                    }
                }
            }
            if (IPStatisticsManager.getInstance().GetIPInBeOperation(s, IPOperaType.BanConnect))
            {
                disableConnect = true;
            }
            if (this.DontAccept || disableConnect)
            {
                try
                {
                    if (disableConnect)
                    {
                        LogManager.WriteLog(LogTypes.Error, string.Format("新远程连接: {0}, 但是客户端IP处于IP过滤中,直接关闭连接:{1}", s.RemoteEndPoint, this.ConnectedSocketsCount), null, true);
                    }
                    else if (this.DontAccept)
                    {
                        LogManager.WriteLog(LogTypes.Error, string.Format("新远程连接: {0}, 但是服务器端处于不接受新连接状态,直接关闭连接:{1}", s.RemoteEndPoint, this.ConnectedSocketsCount), null, true);
                    }
                }
                catch (Exception)
                {
                }
                try
                {
                    s.Shutdown(SocketShutdown.Both);
                }
                catch (Exception)
                {
                }
                try
                {
                    s.Close(30);
                }
                catch (Exception)
                {
                }
                this.StartAccept(e);
            }
            else
            {
                byte[] inOptionValues = new byte[12];
                BitConverter.GetBytes(1U).CopyTo(inOptionValues, 0);
                BitConverter.GetBytes(120000U).CopyTo(inOptionValues, 4);
                BitConverter.GetBytes(5000U).CopyTo(inOptionValues, 8);
                s.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null);
                LingerOption lingerOption = new LingerOption(true, 10);
                s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, lingerOption);
                SocketAsyncEventArgs readEventArgs = null;
                readEventArgs = s.PopReadSocketAsyncEventArgs();
                if (null == readEventArgs)
                {
                    try
                    {
                        LogManager.WriteLog(LogTypes.Error, string.Format("新远程连接: {0}, 但是readPool内的缓存不足,直接关闭连接:{1}", s.RemoteEndPoint, this.ConnectedSocketsCount), null, true);
                    }
                    catch (Exception)
                    {
                    }
                    try
                    {
                        s.Shutdown(SocketShutdown.Both);
                    }
                    catch (Exception)
                    {
                    }
                    try
                    {
                        s.Close(30);
                    }
                    catch (Exception)
                    {
                    }
                    this.StartAccept(e);
                }
                else
                {
                    (readEventArgs.UserToken as AsyncUserToken).CurrentSocket = s;
                    Global._SendBufferManager.Add(s);
                    this.AddSocket(s);
                    try
                    {
                        LogManager.WriteLog(LogTypes.Error, string.Format("新远程连接: {0}, 当前总共: {1}", s.RemoteEndPoint, this.ConnectedSocketsCount), null, true);
                    }
                    catch (Exception)
                    {
                    }
                    if (null != this.SocketConnected)
                    {
                        this.SocketConnected(this, readEventArgs);
                    }
                    s.session.InIpWhiteList = inIpWriteList;
                    s.session.SetSocketTime(0);
                    if (!this._ReceiveAsync(readEventArgs))
                    {
                        this.ProcessReceive(readEventArgs);
                    }
                    this.StartAccept(e);
                }
            }
        }
コード例 #12
0
ファイル: AdminConnection.cs プロジェクト: Cloudxtreme/net
        public void HandleConnection(object unused)
        {
            Thread.Sleep(10);

            LingerOption lingerOption = new LingerOption(true, 10);

            connection.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, lingerOption);

            try
            {
                connection.Connect(ep);
            }
            catch {}

            int     ret;
            decimal dTimeOut = DateTime.Now.ToFileTime();

            string aData = "";
            string bData = "";

            byte[] RecvBytes;

            if (connection.Connected)
            {
                Connected.BeginInvoke(null, null, null, null);
            }

            while (connection.Connected && !disconnect)
            {
                if (connection.Available > 0)
                {
                    RecvBytes = new byte[connection.Available];
                    ret       = connection.Receive(RecvBytes, 0, RecvBytes.Length, SocketFlags.None);
                    aData     = aData + Encoding.ASCII.GetString(RecvBytes).Substring(0, ret);


                    while (aData.IndexOf(newline) > -1)
                    {
                        bData = Regex.Split(aData, newline)[0].ToString();
                        HandleData(bData);
                        aData = aData.Substring((aData.IndexOf(newline) + 2));
                    }
                    dTimeOut = DateTime.Now.ToFileTime();
                }
                else
                {
                    /*
                     * myData.bStayConnected = ((dTimeOut + 9000000000 /* 30 minutes )/* < DateTime.Now.ToFileTime() ? false : true);
                     * /*if (!myData.bStayConnected)
                     * {
                     *      Send("451 Timeout" + newline);
                     * }
                     */
                    Thread.Sleep(1);
                }
            }
            //mySocket.Shutdown(SocketShutdown.Both);
            connection.Close();
            try
            {
                Disconnected.BeginInvoke(null, null, null, null);
            }
            catch {}
        }
コード例 #13
0
        /// <exception cref="System.IO.IOException"></exception>
        public ClientConnection(ClientConnectionManager clientConnectionManager,
                                ClientInvocationService invocationService,
                                int id,
                                Address address,
                                ClientNetworkConfig clientNetworkConfig)
        {
            _clientConnectionManager = clientConnectionManager;
            _id = id;

            var isa           = address.GetInetSocketAddress();
            var socketOptions = clientNetworkConfig.GetSocketOptions();
            var socketFactory = socketOptions.GetSocketFactory() ?? new DefaultSocketFactory();

            _clientSocket = socketFactory.CreateSocket();

            try
            {
                _clientSocket = new Socket(isa.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                _clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);

                var lingerOption = new LingerOption(true, 5);
                if (socketOptions.GetLingerSeconds() > 0)
                {
                    lingerOption.LingerTime = socketOptions.GetLingerSeconds();
                }
                _clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, lingerOption);
                _clientSocket.NoDelay = socketOptions.IsTcpNoDelay();

                _clientSocket.ReceiveTimeout = socketOptions.GetTimeout() > 0 ? socketOptions.GetTimeout() : -1;

                var bufferSize = socketOptions.GetBufferSize() * 1024;
                if (bufferSize < 0)
                {
                    bufferSize = BufferSize;
                }

                _clientSocket.SendBufferSize    = bufferSize;
                _clientSocket.ReceiveBufferSize = bufferSize;

                var connectionTimeout = clientNetworkConfig.GetConnectionTimeout() > -1
                    ? clientNetworkConfig.GetConnectionTimeout()
                    : ConnectionTimeout;
                var socketResult = _clientSocket.BeginConnect(address.GetHost(), address.GetPort(), null, null);

                if (!socketResult.AsyncWaitHandle.WaitOne(connectionTimeout, true) || !_clientSocket.Connected)
                {
                    // NOTE, MUST CLOSE THE SOCKET
                    _clientSocket.Close();
                    throw new IOException("Failed to connect to " + address);
                }
                _sendBuffer    = ByteBuffer.Allocate(BufferSize);
                _receiveBuffer = ByteBuffer.Allocate(BufferSize);

                _builder = new ClientMessageBuilder(invocationService.HandleClientMessage);

                var networkStream = new NetworkStream(_clientSocket, false);
                if (clientNetworkConfig.GetSSLConfig().IsEnabled())
                {
                    var sslStream = new SslStream(networkStream, false,
                                                  (sender, certificate, chain, sslPolicyErrors) =>
                                                  RemoteCertificateValidationCallback(sender, certificate, chain, sslPolicyErrors,
                                                                                      clientNetworkConfig), null);
                    var certificateName = clientNetworkConfig.GetSSLConfig().GetCertificateName() ?? "";
                    sslStream.AuthenticateAsClient(certificateName);
                    _stream = sslStream;
                }
                else
                {
                    _stream = networkStream;
                }
                _live = new AtomicBoolean(true);
            }
            catch (Exception e)
            {
                _clientSocket.Close();
                if (_stream != null)
                {
                    _stream.Close();
                }
                throw new IOException("Cannot connect! Socket error:" + e.Message);
            }
        }
コード例 #14
0
 internal static extern unsafe Error SetLingerOption(SafeHandle socket, LingerOption* option);
コード例 #15
0
        public bool ConnectToOpenCOVER(string host, int port)
        {
            messageQueue = new Queue <COVERMessage>();

            try
            {
                if (toCOVER != null)
                {
                    messageThread.Abort(); // stop reading from the old toCOVER connection
                    toCOVER.Close();
                    toCOVER = null;
                }

                toCOVER = new TcpClient(host, port);
                if (toCOVER.Connected)
                {
                    // Sends data immediately upon calling NetworkStream.Write.
                    toCOVER.NoDelay = true;
                    LingerOption lingerOption = new LingerOption(false, 0);
                    toCOVER.LingerState = lingerOption;

                    NetworkStream s    = toCOVER.GetStream();
                    Byte[]        data = new Byte[256];
                    data[0] = 1;
                    try
                    {
                        //toCOVER.ReceiveTimeout = 1000;
                        s.Write(data, 0, 1);
                        //toCOVER.ReceiveTimeout = 10000;
                    }
                    catch (System.IO.IOException e)
                    {
                        // probably socket closed
                        toCOVER = null;
                        return(false);
                    }

                    int numRead = 0;
                    try
                    {
                        //toCOVER.ReceiveTimeout = 1000;
                        numRead = s.Read(data, 0, 1);
                        //toCOVER.ReceiveTimeout = 10000;
                    }
                    catch (System.IO.IOException e)
                    {
                        // probably socket closed
                        toCOVER = null;
                        return(false);
                    }
                    if (numRead == 1)
                    {
                        // messageThread = new Thread(new ThreadStart(this.handleMessages));

                        // Start the thread
                        //messageThread.Start();
                    }

                    return(true);
                }
                //String errorMessage = "Could not connect to OpenCOVER on "+ host+ ", port "+ Convert.ToString(port);
                //System.Windows.Forms.MessageBox.Show(errorMessage);
            }
            catch
            {
                //String errorMessage = "Connection error while trying to connect to OpenCOVER on " + host + ", port " + Convert.ToString(port);
                //System.Windows.Forms.MessageBox.Show(errorMessage);
            }
            toCOVER = null;
            return(false);
        }
コード例 #16
0
ファイル: Form1.cs プロジェクト: afdhalrizki/radio-client
        private void clientOpenConnection(string _clientIPAddress, string _clientPort)
        {
            openConnection = false;
            LingerOption lingeroption = null;
            string       clientIPTemp; // FCS IP Address
            string       clientPortTemp;

            if (string.IsNullOrEmpty(clientIP.Text))
            {
                clientIPTemp = _clientIPAddress;
            }
            else
            {
                clientIPTemp = clientIP.Text;
            }

            if (string.IsNullOrEmpty(clientPort.Text))
            {
                clientPortTemp = _clientPort;
            }
            else
            {
                clientPortTemp = clientPort.Text;
            }

            if (clientconnectbuttonstate == false) // (clientConnectButton.Text == "Connect")
            {
                if (ValidateIPAddress(clientIPTemp) == false)
                {
                    clientConnectionDetails.Text = "Enter valid IP address";
                    return;
                }

                try
                {
                    ipAddressClientConnect = IPAddress.Parse(clientIPTemp);      ///< Checks for valid IP.
                }
                catch
                {
                    clientConnectionDetails.Text = "Enter valid IP address";
                    return;
                }

                try
                {
                    // Checks if port number is valid.
                    clientPortSelect = (Int32)Convert.ToUInt32(clientPortTemp);
                    if ((clientPortSelect > 65535) || (clientPortSelect < 1))
                    {
                        throw new ArgumentOutOfRangeException();
                    }
                }
                catch
                {
                    clientConnectionDetails.Text = "Port number must be positive value less than 65535.";
                    return;
                }
                clientConnectionDetails.Text = "Trying to connect...";
                clientConnectButton.Text     = "Trying...";
                clientConnectButton.Enabled  = false;
                clientPort.Enabled           = false;
                clientIP.Enabled             = false;
                try
                {
                    clientSocketEndPoint = new IPEndPoint(ipAddressClientConnect, clientPortSelect);
                    tcpClientSocket      = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    lingeroption         = new LingerOption(false, 0);
                    tcpClientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, lingeroption);
                    tcpClientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, false);
                    clientSocketConnect = tcpClientSocket.BeginConnect(clientSocketEndPoint, null, null);
                    /// Sets time-out for BeginConnect procedure.
                    openConnection = clientSocketConnect.AsyncWaitHandle.WaitOne(timeoutMsec, false);
                    if (openConnection == false)
                    {
                        clientConnectionDetails.Text = "Timeout.";
                        tcpClientSocket.Close();
                    }
                }
                catch (SocketException exception)
                {
                    clientConnectionDetails.Text = "Failed. Socket error Code = " + (exception.ErrorCode).ToString();
                }
                catch
                {
                    clientConnectionDetails.Text = "Failed. Unable to connect.";
                }
                clientConnectButton.Enabled = true;
                if (openConnection == false)
                {
                    tcpClientSocket          = null;
                    clientConnectButton.Text = "Connect";
                    clientPort.Enabled       = true;
                    clientIP.Enabled         = true;
                    //tambahan
                    totalBytez = 0;
                    return;
                }
                clientConnectButton.Text     = "Disconnect";
                clientConnectionDetails.Text = "Connected.";
                clientSendButton.Enabled     = true;
                /// New thread to watch reception of data and connectivity.
                threadClientSide = new Thread(() => ClientReceiveProcedure(tcpClientSocket));
                threadClientSide.Start();
                clientDisconnectCommand  = false;
                clientconnectbuttonstate = true;
            }
        }
コード例 #17
0
 internal static extern unsafe Error SetLingerOption(int socket, LingerOption* option);
コード例 #18
0
ファイル: source.cs プロジェクト: ruo2012/samples-1
    // MyTcpClientPropertySetter is just used to illustrate setting and getting various properties of the TcpClient class.
    public static void MyTcpClientPropertySetter()
    {
        TcpClient tcpClient = new TcpClient();

        // <Snippet8>
        // Sets the receive buffer size using the ReceiveBufferSize public property.
        tcpClient.ReceiveBufferSize = 1024;

        // Gets the receive buffer size using the ReceiveBufferSize public property.
        if (tcpClient.ReceiveBufferSize == 1024)
        {
            Console.WriteLine("The receive buffer was successfully set to " + tcpClient.ReceiveBufferSize.ToString());
        }

        // </Snippet8>
        // <Snippet9>
        // Sets the send buffer size using the SendBufferSize public property.
        tcpClient.SendBufferSize = 1024;

        // Gets the send buffer size using the SendBufferSize public property.
        if (tcpClient.SendBufferSize == 1024)
        {
            Console.WriteLine("The send buffer was successfully set to " + tcpClient.SendBufferSize.ToString());
        }

        // </Snippet9>
        // <Snippet10>
        // Sets the receive time out using the ReceiveTimeout public property.
        tcpClient.ReceiveTimeout = 5000;

        // Gets the receive time out using the ReceiveTimeout public property.
        if (tcpClient.ReceiveTimeout == 5000)
        {
            Console.WriteLine("The receive time out limit was successfully set " + tcpClient.ReceiveTimeout.ToString());
        }

        // </Snippet10>
        // <Snippet11>
        // sets the send time out using the SendTimeout public property.
        tcpClient.SendTimeout = 5;

        // gets the send time out using the SendTimeout public property.
        if (tcpClient.SendTimeout == 5)
        {
            Console.WriteLine("The send time out limit was successfully set " + tcpClient.SendTimeout.ToString());
        }

        // </Snippet11>
        // <Snippet12>
        // sets the amount of time to linger after closing, using the LingerOption public property.
        LingerOption lingerOption = new LingerOption(true, 10);

        tcpClient.LingerState = lingerOption;

        // gets the amount of linger time set, using the LingerOption public property.
        if (tcpClient.LingerState.LingerTime == 10)
        {
            Console.WriteLine("The linger state setting was successfully set to " + tcpClient.LingerState.LingerTime.ToString());
        }

        // </Snippet12>
        // <Snippet13>
        // Sends data immediately upon calling NetworkStream.Write.
        tcpClient.NoDelay = true;

        // Determines if the delay is enabled by using the NoDelay property.
        if (tcpClient.NoDelay == true)
        {
            Console.WriteLine("The delay was set successfully to " + tcpClient.NoDelay.ToString());
        }

        // </Snippet13>
        tcpClient.Close();
    }