Example #1
0
        public PgmListener([NotNull] IOThread ioThread, [NotNull] SocketBase socket, [NotNull] Options options)
            : base(ioThread, options)
        {
            m_socket = socket;

            m_ioObject = new IOObject(ioThread);
        }
Example #2
0
        public PgmListener( IOThread ioThread,  SocketBase socket,  Options options)
            : base(ioThread, options)
        {
            m_socket = socket;

            m_ioObject = new IOObject(ioThread);
        }
Example #3
0
 /// <summary>
 /// Create a new TcpListener on the given IOThread and socket.
 /// </summary>
 /// <param name="ioThread">the IOThread for this to live within</param>
 /// <param name="socket">a SocketBase to listen on</param>
 /// <param name="options">socket-related Options</param>
 public TcpListener([NotNull] IOThread ioThread, [NotNull] SocketBase socket, [NotNull] Options options)
     : base(ioThread, options)
 {
     m_ioObject = new IOObject(ioThread);
     m_address = new TcpAddress();
     m_handle = null;
     m_socket = socket;
 }
Example #4
0
 /// <summary>
 /// new
 /// </summary>
 /// <param name="name"></param>
 /// <param name="endPoint"></param>
 /// <param name="host"></param>
 /// <param name="onConnected"></param>
 /// <param name="onDisconnected"></param>
 public SocketConnector(string name,
     EndPoint endPoint,
     SocketBase.IHost host,
     Action<SocketConnector, SocketBase.IConnection> onConnected,
     Action<SocketConnector, SocketBase.IConnection> onDisconnected)
 {
     this.Name = name;
     this.EndPoint = endPoint;
     this.Host = host;
     this._onConnected = onConnected;
     this._onDisconnected = onDisconnected;
 }
Example #5
0
        /// <summary>
        /// new
        /// </summary>
        /// <param name="name"></param>
        /// <param name="endPoint"></param>
        /// <param name="host"></param>
        /// <exception cref="ArgumentNullException">name is null or empty</exception>
        /// <exception cref="ArgumentNullException">endPoint is null</exception>
        /// <exception cref="ArgumentNullException">host is null</exception>
        public SocketListener(string name, IPEndPoint endPoint, SocketBase.IHost host)
        {
            if (string.IsNullOrEmpty(name)) throw new ArgumentNullException("name");
            if (endPoint == null) throw new ArgumentNullException("endPoint");
            if (host == null) throw new ArgumentNullException("host");

            this.Name = name;
            this.EndPoint = endPoint;
            this._host = host;

            this._ae = new SocketAsyncEventArgs();
            this._ae.Completed += new EventHandler<SocketAsyncEventArgs>(this.AcceptAsyncCompleted);
        }
Example #6
0
        /// <summary>
        /// Create a return a new session.
        /// The specific subclass of SessionBase that is created is dictated by the SocketType specified by the options argument.
        /// </summary>
        /// <param name="ioThread">the <c>IOThread</c> for this session to run in</param>
        /// <param name="connect">whether to immediately connect</param>
        /// <param name="socket">the socket to connect</param>
        /// <param name="options">an <c>Options</c> that provides the SocketType that dictates which type of session to create</param>
        /// <param name="addr">an <c>Address</c> object that specifies the protocol and address to connect to</param>
        /// <returns>the newly-created instance of whichever subclass of SessionBase is specified by the options</returns>
        /// <exception cref="InvalidException">The socket must be of the correct type.</exception>

        public static SessionBase Create(IOThread ioThread, bool connect, SocketBase socket, Options options, Address addr)
        {
            switch (options.SocketType)
            {
            case ZmqSocketType.Req:
                return(new Req.ReqSession(ioThread, connect, socket, options, addr));

            case ZmqSocketType.Dealer:
                return(new Dealer.DealerSession(ioThread, connect, socket, options, addr));

            case ZmqSocketType.Rep:
                return(new Rep.RepSession(ioThread, connect, socket, options, addr));

            case ZmqSocketType.Router:
                return(new Router.RouterSession(ioThread, connect, socket, options, addr));

            case ZmqSocketType.Pub:
                return(new Pub.PubSession(ioThread, connect, socket, options, addr));

            case ZmqSocketType.Xpub:
                return(new XPub.XPubSession(ioThread, connect, socket, options, addr));

            case ZmqSocketType.Sub:
                return(new Sub.SubSession(ioThread, connect, socket, options, addr));

            case ZmqSocketType.Xsub:
                return(new XSub.XSubSession(ioThread, connect, socket, options, addr));

            case ZmqSocketType.Push:
                return(new Push.PushSession(ioThread, connect, socket, options, addr));

            case ZmqSocketType.Pull:
                return(new Pull.PullSession(ioThread, connect, socket, options, addr));

            case ZmqSocketType.Pair:
                return(new Pair.PairSession(ioThread, connect, socket, options, addr));

            case ZmqSocketType.Stream:
                return(new Stream.StreamSession(ioThread, connect, socket, options, addr));

            default:
                throw new InvalidException("SessionBase.Create called with invalid SocketType of " + options.SocketType);
            }
        }
Example #7
0
        /// <summary>
        /// Un-register the given address/socket, by removing it from the contained list of endpoints.
        /// </summary>
        /// <param name="address">the (string) address denoting the endpoint to unregister</param>
        /// <param name="socket">the socket associated with that endpoint</param>
        /// <returns>true if the endpoint having this address and socket is found, false otherwise</returns>
        public bool UnregisterEndpoint([NotNull] string address, [NotNull] SocketBase socket)
        {
            lock (m_endpointsSync)
            {
                Endpoint endpoint;
                if (!m_endpoints.TryGetValue(address, out endpoint))
                {
                    return(false);
                }

                if (socket != endpoint.Socket)
                {
                    return(false);
                }

                m_endpoints.Remove(address);
                return(true);
            }
        }
Example #8
0
        public void Start(int port)
        {
            //定时器
            //timer.Elapsed += new System.Timers.ElapsedEventHandler(HandleMainTimer);
            //timer.AutoReset = false;
            //timer.Enabled = true;
            //链接池
            clients = new SocketBase[maxConn];
            for (int i = 0; i < maxConn; i++)
            {
                clients[i] = new SocketBase();
            }

            ServerEvent.GetInstance.SendPackage(ServerEvent.EventType.EVENT_SEND_PACKAGE, new ServerPackage(10, 20, 30));
            tcpListener = new TcpListener(new IPEndPoint(IPAddress.Any, port));
            tcpListener.Start();
            tcpListener.BeginAcceptTcpClient(AcceptCb, tcpListener);
            Console.WriteLine("[服务器]启动成功");
        }
Example #9
0
        internal NetMQSocket(ZmqSocketType socketType, string?connectionString, DefaultAction defaultAction)
        {
            m_socketHandle    = NetMQConfig.Context.CreateSocket(socketType);
            m_netMqSelector   = new NetMQSelector();
            Options           = new SocketOptions(this);
            m_socketEventArgs = new NetMQSocketEventArgs(this);

            Options.Linger = NetMQConfig.Linger;

            if (!Strings.IsNullOrEmpty(connectionString))
            {
                var endpoints = connectionString
                                .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                .Select(a => a.Trim())
                                .Where(a => !string.IsNullOrEmpty(a));

                foreach (var endpoint in endpoints)
                {
                    switch (endpoint[0])
                    {
                    case '@':
                        Bind(endpoint.Substring(1));
                        break;

                    case '>':
                        Connect(endpoint.Substring(1));
                        break;

                    default:
                        if (defaultAction == DefaultAction.Connect)
                        {
                            Connect(endpoint);
                        }
                        else
                        {
                            Bind(endpoint);
                        }
                        break;
                    }
                }
            }
        }
        static void Main(string[] args)
        {
            byte[] readcmdexam = new byte[] { 0x03, 0x00, 0x00, 0x1f, 0x02, 0xf0, 0x80, 0x32, 0x10, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x0e, 0x00 };

            SiemensS7Net s7 = new SiemensS7Net();
            bool         ret;

            Logger.Infor("enter plc init");
            ret = s7.init_plc_Connect();
            Logger.Infor("init plc ok");
            //s7.writeByteData(aaa, 2, 29, 1, 4);
            //s7.writeByteData(readcmdexam);
            SocketBase.SocketSend(readcmdexam);

            /*SocketBase.initSocketBase();
             * byte[] ss = new byte[] { 0x01};
             * SocketBase.SocketSend(ss);
             * byte[] aa = SocketBase.SocketRec();
             *
             * //Console.ReadKey();*/



            #region 测试

            /* Stopwatch st = new Stopwatch();
             * st.Start();
             * string ss ="// SocketBase.SocketBase sk = new SocketBase.SocketBase()";
             *
             *
             * System.Threading.Tasks.Parallel.For(0, 1000, x =>
             * {
             *     Logger.Error(ss + x.ToString());
             *     Logger.Infor("test" + x.ToString());
             *     //Console.WriteLine(x);
             *
             * });
             * st.Stop();
             * Console.WriteLine(st.ElapsedMilliseconds);
             * Console.ReadKey();*/
            #endregion
        }
Example #11
0
        /// <summary>
        /// Create a return a new session.
        /// The specific subclass of SessionBase that is created is dictated by the SocketType specified by the options argument.
        /// </summary>
        /// <param name="ioThread">the <c>IOThread</c> for this session to run in</param>
        /// <param name="connect">whether to immediately connect</param>
        /// <param name="socket">the socket to connect</param>
        /// <param name="options">an <c>Options</c> that provides the SocketType that dictates which type of session to create</param>
        /// <param name="addr">an <c>Address</c> object that specifies the protocol and address to connect to</param>
        /// <returns>the newly-created instance of whichever subclass of SessionBase is specified by the options</returns>
        /// <exception cref="InvalidException">The socket must be of the correct type.</exception>
        public static SessionBase Create(IOThread ioThread, bool connect, SocketBase socket, Options options, Address addr)
        {
            switch (options.SocketType)
            {
            case ZmqSocketType.Req:
                return(new Req.ReqSession(ioThread, connect, socket, options, addr));

            case ZmqSocketType.Radio:
                return(new Radio.RadioSession(ioThread, connect, socket, options, addr));

            case ZmqSocketType.Dish:
                return(new Dish.DishSession(ioThread, connect, socket, options, addr));

            case ZmqSocketType.Dealer:
            case ZmqSocketType.Rep:
            case ZmqSocketType.Router:
            case ZmqSocketType.Pub:
            case ZmqSocketType.Xpub:
            case ZmqSocketType.Sub:
            case ZmqSocketType.Xsub:
            case ZmqSocketType.Push:
            case ZmqSocketType.Pull:
            case ZmqSocketType.Pair:
            case ZmqSocketType.Stream:
            case ZmqSocketType.Peer:
            case ZmqSocketType.Server:
            case ZmqSocketType.Client:
            case ZmqSocketType.Gather:
            case ZmqSocketType.Scatter:
                if (options.CanSendHelloMsg && options.HelloMsg != null)
                {
                    return(new HelloMsgSession(ioThread, connect, socket, options, addr));
                }
                else
                {
                    return(new SessionBase(ioThread, connect, socket, options, addr));
                }

            default:
                throw new InvalidException("SessionBase.Create called with invalid SocketType of " + options.SocketType);
            }
        }
Example #12
0
        public void TCPServerDataContext()
        {
            ConnectionsInfo = new ObservableCollection <TCPServerConnectionsInfo>();

            IPAddrItemsSource     = new ObservableCollection <IPAddress>();
            IPAddrInfoItemsSource = new ObservableCollection <string>();
            SocketBase _SocketBase = new SocketBase();

            _SocketBase.GitNetworkInterface(IPAddrItemsSource, IPAddrInfoItemsSource);
            IPAddrText          = string.Empty;
            IPAddrSelectedIndex = 0;

            Port = 8088;

            IPAddrEnable = true;
            PortEnable   = true;

            Brush     = Brushes.Red;
            OpenClose = string.Format(cultureInfo, "TCP 侦听");
        }
Example #13
0
 public void Close()
 {
     for (int i = 0; i < clients.Length; i++)
     {
         SocketBase con = clients[i];
         if (con == null)
         {
             continue;
         }
         if (!con.isUsed)
         {
             continue;
         }
         lock (con)
         {
             con.Close();
         }
     }
     tcpListener.Stop();
 }
Example #14
0
 public int NewIndex()
 {
     if (clients == null)
     {
         return(-1);
     }
     for (int i = 0; i < clients.Length; i++)
     {
         if (clients[i] == null)
         {
             clients[i] = new SocketBase();
             return(i);
         }
         else if (clients[i].isUsed == false)
         {
             return(i);
         }
     }
     return(-1);
 }
        public void Plug(IOThread ioThread, SessionBase session)
        {
            Debug.Assert(!m_plugged);
            m_plugged = true;

            // Connect to session object.
            Debug.Assert(m_session == null);
            Debug.Assert(session != null);
            m_session = session;
            m_socket  = m_session.Socket;

            m_ioObject = new IOObject(null);
            m_ioObject.SetHandler(this);

            // Connect to I/O threads poller object.
            m_ioObject.Plug(ioThread);
            m_ioObject.AddSocket(m_handle);
            m_ioEnabled = true;

            FeedAction(Action.Start, SocketError.Success, 0);
        }
Example #16
0
        public bool init_plc_Connect() //与plc连接的初始化
        {
            bool status;               //判断返回值是否对的标志

            //SocketBase sk = new SocketBase();

            if (SocketBase.initSocketBase())
            {
                SocketBase.SocketSend(plcHead1);
                //Console.ReadKey();
                if (SocketBase.SocketRec().Length == 22)
                {
                    Logger.Infor("handshake first done");
                    SocketBase.SocketSend(plcHead2);
                    byte[] res = SocketBase.SocketRec();
                    if (res.Length == 27)
                    {
                        status = true;
                        Logger.Infor("handshake second done,init ok " + res);
                    }
                    else
                    {
                        status = false;
                        Logger.Error("handshake second failed");
                    }
                }
                else
                {
                    //Console.WriteLine("rec {0}", SocketBase.SocketRec());
                    Logger.Error("handshake first error,plc init failed");
                    status = false;
                }
            }
            else
            {
                status = false;
            }
            return(status);
        }
        /// <inheritdoc />
        protected override void ClientConnected(SocketBase client)
        {
            HorseClient horseClient = (HorseClient)client;

            horseClient.Events = Events;
            if (horseClient.DeliveryContainer is TypeDeliveryContainer container)
            {
                container.DefaultConfiguration = Observer.Configurator;
            }

            if (ContentSerializer != null)
            {
                horseClient.JsonSerializer = ContentSerializer;
            }

            base.ClientConnected(client);

            if (AutoSubscribe)
            {
                _ = SubscribeToAllImplementedQueues(true, DisconnectionOnAutoJoinFailure);
            }
        }
Example #18
0
        /// <summary>
        /// Process websocket message
        /// </summary>
        private async Task ProcessMessage(IConnectionInfo info, SocketBase socket, WebSocketMessage message)
        {
            switch (message.OpCode)
            {
            case SocketOpCode.Binary:
            case SocketOpCode.UTF8:
                //if user makes a mistake in received method, we should not interrupt connection handling
                try
                {
                    await _handler.Received(_server, info, (WsServerSocket)socket, message);
                }
                catch (Exception e)
                {
                    if (_server.Logger != null)
                    {
                        _server.Logger.LogException("Unhandled Exception", e);
                    }
                }

                break;

            //close the connection if terminate requested
            case SocketOpCode.Terminate:
                info.Close();
                break;

            //if client sends a ping message, response with pong
            case SocketOpCode.Ping:
                await socket.SendAsync(PredefinedMessages.PONG);

                break;

            //client sent response pong to ping message
            case SocketOpCode.Pong:
                socket.KeepAlive();
                break;
            }
        }
Example #19
0
        public void Plug(IOThread ioThread, SessionBase session)
        {
            m_session = session;

            m_socket = session.Socket;

            m_ioObject = new IOObject(null);
            m_ioObject.SetHandler(this);
            m_ioObject.Plug(ioThread);
            m_ioObject.AddSocket(m_handle);

            DropSubscriptions();

            var msg = new Msg();

            msg.InitEmpty();

            // push message to the session because there is no identity message with pgm
            session.PushMsg(ref msg);

            m_state = State.Receiving;
            BeginReceive();
        }
        // *** Old text based networking, still in ShellViewModel ***

        // Finishes receiving data from client, passes message to handler
        public override void ReceiveCallback(IAsyncResult asyncResult)
        {
            // Recreates client socket to handle connection
            Socket clientSocket = (Socket)asyncResult.AsyncState;

            // Stops infinite receive loop when client disconnects
            if (!SocketBase.IsConnected(clientSocket))
            {
                PrintMessage($"Client {ClientSocketsInverse[clientSocket]} has disconnected");

                // Removes client from dictionaries of connected clients
                ClientSockets.Remove(ClientSocketsInverse[clientSocket]);
                ClientSocketsInverse.Remove(clientSocket);

                return;
            }

            // Parent method called to finish receiving data and call handler
            base.ReceiveCallback(asyncResult);

            // Continues infinite receive loop
            Receive(clientSocket);
        }
Example #21
0
        /// <summary>
        /// Reads the string message and if any method is subscribed the model event with On method, they will be called.
        /// </summary>
        public virtual void Read(SocketBase client, string message)
        {
            int type = Reader.ReadType(message);

            if (!_descriptors.ContainsKey(type))
            {
                return;
            }

            PackageDescriptor descriptor = _descriptors[type];

            ISerializableModel model = Reader.Read(descriptor.Type, message, true);

            if (model == null)
            {
                return;
            }

            foreach (var action in descriptor.Actions)
            {
                action.DynamicInvoke(client, model);
            }
        }
Example #22
0
        /// <summary>
        ///     Destroy the given socket - which means to remove it from the list of active sockets,
        ///     and add it to the list of unused sockets to be terminated.
        /// </summary>
        /// <param name="socket">the socket to destroy</param>
        /// <remarks>
        ///     If this was the last socket, then stop the reaper.
        /// </remarks>
        public void DestroySocket([NotNull] SocketBase socket)
        {
            // Free the associated thread slot.
            lock (this.m_slotSync)
            {
                int threadId = socket.ThreadId;
                this.m_emptySlots.Push(threadId);
                this.m_slots[threadId].Close();
                this.m_slots[threadId] = null;

                // Remove the socket from the list of sockets.
                this.m_sockets.Remove(socket);

                // If zmq_term() was already called and there are no more socket
                // we can ask reaper thread to terminate.
                if (this.m_terminating && this.m_sockets.Count == 0)
                {
                    this.m_reaper.Stop();
                }
            }

            //LOG.debug("Released Slot [" + socket_ + "] ");
        }
Example #23
0
        /// <summary>
        /// 初始化方法 -> Initialize method
        /// </summary>
        /// <param name="siemens">指定西门子的型号 -> Designation of Siemens</param>
        /// <param name="ipAddress">Ip地址 -> IpAddress</param>
        private void Initialization(SiemensType siemens, string ip)//plc型号选择,默认是1200,ip默认为127.0.0.1
        {
            WordLength = 2;

            IpAddress  = ip;
            Port       = 102;
            CurrentPlc = siemens;

            switch (siemens)
            {
            case SiemensType.S1200: plcHead1[21] = 0; break;

            case SiemensType.S300: plcHead1[21] = 2; break;

            case SiemensType.S400: plcHead1[21] = 3; plcHead1[17] = 0x00; break;

            case SiemensType.S1500: plcHead1[21] = 0; break;

            case SiemensType.S200Smart:
            {
                plcHead1 = plcHead1_200smart;
                plcHead2 = plcHead2_200smart;
                break;
            }

            case SiemensType.S200:
            {
                plcHead1 = plcHead1_200;
                plcHead2 = plcHead2_200;
                break;
            }

            default: plcHead1[18] = 0; break;
            }
            SocketBase sk = new SocketBase();
            //sk.initSocketBase(ip, Port);
        }
Example #24
0
        /// <summary>
        /// Create a new NetMQSocket with the given <see cref="ZmqSocketType"/>.
        /// </summary>
        /// <param name="socketType">Type of socket to create</param>
        internal NetMQSocket(ZmqSocketType socketType, string connectionString, DefaultAction defaultAction)
        {
            m_socketHandle    = NetMQConfig.Context.CreateSocket(socketType);
            m_selector        = new Selector();
            Options           = new SocketOptions(this);
            m_socketEventArgs = new NetMQSocketEventArgs(this);

            Options.Linger = NetMQConfig.Linger;

            if (!string.IsNullOrEmpty(connectionString))
            {
                var endpoints =
                    connectionString.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                    .Select(a => a.Trim()).Where(a => !string.IsNullOrEmpty(a));

                foreach (string endpoint in endpoints)
                {
                    if (endpoint[0] == '@')
                    {
                        Bind(endpoint.Substring(1));
                    }
                    else if (endpoint[0] == '>')
                    {
                        Connect(endpoint.Substring(1));
                    }
                    else if (defaultAction == DefaultAction.Connect)
                    {
                        Connect(endpoint);
                    }
                    else
                    {
                        Bind(endpoint);
                    }
                }
            }
        }
Example #25
0
        private void AcceptCb(IAsyncResult ar)
        {
            try
            {
                TcpListener listener = (TcpListener)ar.AsyncState;
                TcpClient   client   = (TcpClient)listener.EndAcceptTcpClient(ar);
                int         index    = NewIndex();

                if (index < 0)
                {
                    client.Close();
                    Console.WriteLine("[警告]链接已满");
                }
                else
                {
                    SocketBase socketBase = clients[index];
                    socketBase.Init(client);
                    //string adr = socketBase.GetAddress();
                    //Console.WriteLine("客户端连接 [" + adr + "] conn池ID:" + index);
                    //MessageData messageData = new MessageData();
                    //string msg = " [" + plazaSession.GetAddress() + "] 加入聊天房间,当前房间人数[" + GetOnlineCount() + "]";
                    //plazaSession.client.GetStream().BeginRead(plazaSession.byteBuffer, 0, plazaSession.GetMaxRead(), new AsyncCallback(ReceiveCb), plazaSession);
                    //plazaSession.client
                    //AddMessage(conn, ref messageData, 0, 3, msg);
                    //Broadcast(conn, messageData,true);
                    //conn.socket.BeginReceive(conn.readBuffer,
                    //                         conn.bufferCount, conn.Buffremain(),
                    //                         SocketFlags.None, ReceiveCb, conn);
                }
                tcpListener.BeginAcceptTcpClient(AcceptCb, tcpListener);
            }
            catch (Exception e)
            {
                Console.WriteLine("AcceptCb失败:" + e.Message);
            }
        }
Example #26
0
 /// <summary>
 /// 断开连接
 /// </summary>
 /// <param name="connection"></param>
 /// <param name="ex"></param>
 private void OnDisconnected(SocketBase.IConnection connection, Exception ex)
 {
     connection.Disconnected -= this.OnDisconnected;
     //delay reconnect 20ms ~ 200ms
     if (!this._isStop) SocketBase.Utils.TaskEx.Delay(new Random().Next(20, 200), this.Start);
     //fire disconnected event
     this._onDisconnected(this, connection);
 }
Example #27
0
        public void Plug(IOThread ioThread, SessionBase session)
        {
            Debug.Assert(!m_plugged);
            m_plugged = true;

            //  Connect to session object.
            Debug.Assert(m_session == null);
            Debug.Assert(session != null);
            m_session = session;
            m_socket = m_session.Socket;

            m_ioObject = new IOObject(null);
            m_ioObject.SetHandler(this);

            //  Connect to I/O threads poller object.
            m_ioObject.Plug(ioThread);
            m_ioObject.AddSocket(m_handle);
            m_ioEnabled = true;

            FeedAction(Action.Start, SocketError.Success, 0);
        }
 /// <summary>
 /// reply
 /// </summary>
 /// <param name="connection"></param>
 /// <param name="payload"></param>
 public void Reply(SocketBase.IConnection connection, byte[] payload)
 {
     var packet = PacketBuilder.ToAsyncBinary(this.CmdName, this.SeqID, payload);
     connection.BeginSend(packet);
 }
Example #29
0
 public SelectItem(SocketBase socket, PollEvents @event)
 {
     Socket = socket;
     Event = @event;
 }
Example #30
0
 /// <summary>
 /// Create a new SubscriberSocket based upon the given SocketBase.
 /// </summary>
 /// <param name="socketHandle">the SocketBase to create the new socket from</param>
 internal SubscriberSocket(SocketBase socketHandle)
     : base(socketHandle)
 {
 }
Example #31
0
 public RouterSession([NotNull] IOThread ioThread, bool connect, [NotNull] SocketBase socket, [NotNull] Options options, [NotNull] Address addr)
     : base(ioThread, connect, socket, options, addr)
 {
 }
Example #32
0
File: Rep.cs Project: fhchina/netmq
 public RepSession(IOThread ioThread, bool connect,
                   SocketBase socket, Options options,
                   Address addr)
     : base(ioThread, connect, socket, options, addr)
 {
 }
Example #33
0
File: Req.cs Project: awb99/netmq
 public ReqSession( IOThread ioThread, bool connect,  SocketBase socket,  Options options,  Address addr)
     : base(ioThread, connect, socket, options, addr)
 {
     m_state = State.Identity;
 }
 partial void SetDefaultCulture(SocketBase.Config.IRootConfig rootConfig)
 {
     if (!string.IsNullOrEmpty(rootConfig.DefaultCulture))
         CultureInfo.DefaultThreadCurrentCulture = new CultureInfo(rootConfig.DefaultCulture);
 }
Example #35
0
        /// <summary>
        /// on connected
        /// </summary>
        /// <param name="node"></param>
        /// <param name="connection"></param>
        private void OnConnected(SocketConnector node, SocketBase.IConnection connection)
        {
            SocketBase.IConnection oldConnection = null;
            bool isActive = false; //node is active

            lock (this)
            {
                //remove exists connection by name.
                if (this._dicConnections.TryGetValue(node.Name, out oldConnection)) this._dicConnections.Remove(node.Name);

                isActive = this._dicNodes.ContainsKey(node.Name);
                if (isActive) this._dicConnections[node.Name] = connection;

                this._arrConnections = this._dicConnections.Values.ToArray();
                this._hashConnections = new ConsistentHashContainer<SocketBase.IConnection>(this._dicConnections);
            }

            //disconect old connection.
            if (oldConnection != null) oldConnection.BeginDisconnect();
            //disconnect not active node connection.
            if (!isActive) { connection.BeginDisconnect(); return; }
            //fire connected event.
            this.Connected(node.Name, connection);
        }
Example #36
0
        public StreamEngine(AsyncSocket handle, Options options, string endpoint)
        {
            m_handle = handle;
            m_insize = 0;
            m_ioEnabled = false;
            m_sendingState = SendState.Idle;
            m_receivingState = ReceiveState.Idle;
            m_outsize = 0;
            m_session = null;
            m_options = options;
            m_plugged = false;
            m_endpoint = endpoint;
            m_socket = null;
            m_encoder = null;
            m_decoder = null;
            m_actionsQueue = new Queue<StateMachineAction>();

            //  Set the socket buffer limits for the underlying socket.
            if (m_options.SendBuffer != 0)
            {
                m_handle.SendBufferSize = m_options.SendBuffer;
            }
            if (m_options.ReceiveBuffer != 0)
            {
                m_handle.ReceiveBufferSize = m_options.ReceiveBuffer;
            }
        }
Example #37
0
 protected void UnregisterEndpoints([NotNull] SocketBase socket)
 {
     m_ctx.UnregisterEndpoints(socket);
 }
Example #38
0
 protected virtual void ProcessReap([NotNull] SocketBase socket)
 {
     // Overridden by Reaper
     throw new NotSupportedException();
 }
Example #39
0
File: Rep.cs Project: awb99/netmq
 public RepSession( IOThread ioThread, bool connect,  SocketBase socket,  Options options,  Address addr)
     : base(ioThread, connect, socket, options, addr)
 {}
Example #40
0
        /// <summary>
        /// on connected
        /// </summary>
        /// <param name="node"></param>
        /// <param name="connection"></param>
        private void OnConnected(SocketConnector node, SocketBase.IConnection connection)
        {
            //fire connected event.
            this.Connected(node.Name, connection);

            bool isActive = false;
            SocketBase.IConnection oldConnection = null;
            lock (this)
            {
                //remove exists connection by name.
                if (this._dicConnections.TryGetValue(node.Name, out oldConnection)) this._dicConnections.Remove(node.Name);
                //add curr connection to list if node is active
                if (isActive = this._dicNodes.ContainsKey(node.Name)) this._dicConnections[node.Name] = connection;

                this._arrConnections = this._dicConnections.Values.ToArray();
                this._hashConnections = new ConsistentHashContainer<SocketBase.IConnection>(this._dicConnections);
            }
            //disconect old connection.
            if (oldConnection != null) oldConnection.BeginDisconnect();
            //disconnect not active node connection.
            if (!isActive) connection.BeginDisconnect();
            //fire server available event.
            if (isActive && this.ServerAvailable != null) this.ServerAvailable(node.Name, connection);
        }
 public bool Setup(IBootstrap bootstrap, IServerConfig config, SocketBase.Provider.ProviderFactoryInfo[] factories)
 {
     throw new NotSupportedException();
 }
Example #42
0
        /// <summary>
        /// on disconnected
        /// </summary>
        /// <param name="node"></param>
        /// <param name="connection"></param>
        private void OnDisconnected(SocketConnector node, SocketBase.IConnection connection)
        {
            lock (this)
            {
                if (!this._dicConnections.Remove(node.Name)) return;

                this._arrConnections = this._dicConnections.Values.ToArray();
                this._hashConnections = new ConsistentHashContainer<SocketBase.IConnection>(this._dicConnections);
            }
        }
Example #43
0
 internal PairSocket(SocketBase socketHandle)
     : base(socketHandle)
 {
 }
Example #44
0
 /// <summary>
 /// new
 /// </summary>
 /// <param name="host"></param>
 /// <exception cref="ArgumentNullException">host is null</exception>
 public DefaultServerPool(SocketBase.IHost host)
 {
     if (host == null) throw new ArgumentNullException("host");
     this._host = host;
 }
Example #45
0
 /// <summary>
 /// Creates a thread socket of type <paramref name="socketType"/>
 /// </summary>
 /// <param name="socketType"></param>
 protected internal ThreadSafeSocket(ZmqSocketType socketType)
 {
     m_socketHandle = NetMQConfig.Context.CreateSocket(socketType);
     Options        = new ThreadSafeSocketOptions(m_socketHandle);
 }
Example #46
0
        /// <summary>
        /// Create a new TcpConnector object.
        /// </summary>
        /// <param name="ioThread">the I/O-thread for this TcpConnector to live on.</param>
        /// <param name="session">the session that will contain this</param>
        /// <param name="options">Options that define this new TcpC</param>
        /// <param name="addr">the Address for this Tcp to connect to</param>
        /// <param name="delayedStart">this boolean flag dictates whether to wait before trying to connect</param>
        public TcpConnector([NotNull] IOThread ioThread, [NotNull] SessionBase session, [NotNull] Options options, [NotNull] Address addr, bool delayedStart)
            : base(ioThread, options)
        {
            m_ioObject = new IOObject(ioThread);
            m_addr = addr;
            m_s = null;
            m_handleValid = false;
            m_delayedStart = delayedStart;
            m_timerStarted = false;
            m_session = session;
            m_currentReconnectIvl = m_options.ReconnectIvl;

            Debug.Assert(m_addr != null);
            m_endpoint = m_addr.ToString();
            m_socket = session.Socket;
        }
Example #47
0
 protected void SendReap([NotNull] SocketBase socket)
 {
     SendCommand(new Command(m_ctx.GetReaper(), CommandType.Reap, socket));
 }
Example #48
0
 /// <summary>
 /// Create a new IpcListener with the given IOThread, socket, and Options.
 /// </summary>
 /// <param name="ioThread"></param>
 /// <param name="socket">the SocketBase to listen to</param>
 /// <param name="options">an Options value that dictates the settings for this IpcListener</param>
 public IpcListener( IOThread ioThread,  SocketBase socket,  Options options)
     : base(ioThread, socket, options)
 {
     m_address = new IpcAddress();
 }
Example #49
0
 protected bool UnregisterEndpoint([NotNull] string addr, [NotNull] SocketBase socket)
 {
     return(m_ctx.UnregisterEndpoint(addr, socket));
 }
Example #50
0
        /// <summary>
        /// begin connect
        /// </summary>
        /// <param name="endPoint"></param>
        /// <param name="host"></param>
        /// <param name="callback"></param>
        /// <exception cref="ArgumentNullException">endPoint is null</exception>
        /// <exception cref="ArgumentNullException">host is null</exception>
        /// <exception cref="ArgumentNullException">callback is null</exception>
        static public void BeginConnect(EndPoint endPoint, SocketBase.IHost host, Action<SocketBase.IConnection> callback)
        {
            if (endPoint == null) throw new ArgumentNullException("endPoint");
            if (host == null) throw new ArgumentNullException("host");
            if (callback == null) throw new ArgumentNullException("callback");

            var socket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                socket.BeginConnect(endPoint, ar =>
                {
                    bool success = false;
                    try { socket.EndConnect(ar); success = true; }
                    catch { }

                    if (success)
                    {
                        socket.NoDelay = true;
                        socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
                        socket.ReceiveBufferSize = host.SocketBufferSize;
                        socket.SendBufferSize = host.SocketBufferSize;
                        callback(new SocketBase.DefaultConnection(host.NextConnectionID(), socket, host));
                    }
                    else callback(null);
                }, null);
            }
            catch { callback(null); }
        }
Example #51
0
 protected void DestroySocket([NotNull] SocketBase socket)
 {
     m_ctx.DestroySocket(socket);
 }
 /// <summary>
 /// add
 /// </summary>
 /// <param name="connection"></param>
 /// <returns></returns>
 /// <exception cref="ArgumentNullException">connection is null</exception>
 public bool Add(SocketBase.IConnection connection)
 {
     if (connection == null) throw new ArgumentNullException("connection");
     return this._dic.TryAdd(connection.ConnectionID, connection);
 }
Example #53
0
        /// <summary>
        /// begin connect
        /// </summary>
        /// <param name="endPoint"></param>
        /// <param name="host"></param>
        /// <param name="callback"></param>
        /// <exception cref="ArgumentNullException">endPoint is null</exception>
        /// <exception cref="ArgumentNullException">host is null</exception>
        /// <exception cref="ArgumentNullException">callback is null</exception>
        static public void BeginConnect(EndPoint endPoint, SocketBase.IHost host, Action<SocketBase.IConnection> callback)
        {
            if (endPoint == null) throw new ArgumentNullException("endPoint");
            if (host == null) throw new ArgumentNullException("host");
            if (callback == null) throw new ArgumentNullException("callback");

            SocketBase.Log.Trace.Debug(string.Concat("begin connect to ", endPoint.ToString()));

            var socket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                socket.BeginConnect(endPoint, ar =>
                {
                    try
                    {
                        socket.EndConnect(ar);
                        socket.NoDelay = true;
                        socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
                        socket.ReceiveBufferSize = host.SocketBufferSize;
                        socket.SendBufferSize = host.SocketBufferSize;
                    }
                    catch (Exception ex)
                    {
                        try
                        {
                            socket.Close();
                            socket.Dispose();
                        }
                        catch { }

                        SocketBase.Log.Trace.Error(ex.Message, ex);
                        callback(null); return;
                    }

                    callback(new SocketBase.DefaultConnection(host.NextConnectionID(), socket, host));
                }, null);
            }
            catch (Exception ex)
            {
                SocketBase.Log.Trace.Error(ex.Message, ex);
                callback(null);
            }
        }
 /// <summary>
 /// reply
 /// </summary>
 /// <param name="connection"></param>
 /// <param name="value"></param>
 public void Reply(SocketBase.IConnection connection, string value)
 {
     connection.BeginSend(PacketBuilder.ToCommandLine(value));
 }