SetSocketOption() public method

public SetSocketOption ( SocketOptionLevel optionLevel, SocketOptionName optionName, bool optionValue ) : void
optionLevel SocketOptionLevel
optionName SocketOptionName
optionValue bool
return void
        public bool initializeConnection()
        {
            try
            {
                m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                m_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);

                m_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);

                m_socket.SendTimeout = 5000;
                m_socket.ReceiveTimeout = 5000;

                m_frm.Print("Connecting to " + ECCServerIP + " at port " + ECCServerPort + " ...");
                m_socket.Connect(ECCServerIP, Convert.ToInt32(ECCServerPort));
            }
            catch (Exception ex)
            {
                m_frm.Print("Error!Failed to connect to ECC server!" + ex.Message);
                return false;
            }

            if (!Authenticate())
                return false;

            return true;
        }
        public void Connect()
        {
            var hostEntry = Dns.GetHostEntry(config.Url);
            var address = hostEntry.AddressList[0];
            var endpoint = new IPEndPoint(IPAddress.Loopback, config.Port);

            client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            client.Connect(endpoint);

            client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, config.BufferSize);
            client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, config.BufferSize);

            stream = new NetworkStream(client, true);

            serverProperties = ReadServerProperties(client);

            var reader = serverProperties.CreateReader();
            var writer = serverProperties.CreateWriter();

            if (serverProperties.AuthenticateRequired)
                TryLogin(writer, config.Username, config.Password);

            sender = new VanillaDataStorageSender(this, name, writer, snapshotManager, config.Serializer, mapper);
            receiver = new VanillaDataStorageReceiver(this, name, reader, config.Serializer, mapper);
            sender.Start();
            receiver.Start();
        }
Example #3
0
    private bool Connect(string ip, int port)
    {
        try
        {
            if (port == 0 || ip == "")
            {
                return(false);
            }
            Debug.Log("connect battle server " + ip + ":" + port);

            IPAddress     ipAddress;
            AddressFamily af;
            bool          ok = Misc.Utils.IPV4ToIPV6(ip, out ipAddress, out af);
            this.TryCloseSocket();
            _inner_socket = new Socket(af, System.Net.Sockets.SocketType.Stream, ProtocolType.Tcp);
            _inner_socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
            _inner_socket.Connect(new IPEndPoint(ipAddress, port));
            _inner_socket.Blocking = true;
            _inner_socket.NoDelay  = true;
            _inner_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, 1024 * 16);
            _inner_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, 1024 * 16);
            this.isConnected = true;
        }
        catch (Exception e)
        {
            this.isConnected = false;
            _inner_socket    = null;
            Debug.Log(e.Message);
            return(false);
        }
        return(true);
    }
        /// <summary>
        /// Starts to listen
        /// </summary>
        /// <param name="config">The server config.</param>
        /// <returns></returns>
        public override bool Start(IServerConfig config)
        {
            m_ListenSocket = new Socket(this.Info.EndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                m_ListenSocket.Bind(this.Info.EndPoint);
                m_ListenSocket.Listen(m_ListenBackLog);

                m_ListenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
                m_ListenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
                //
                m_ListenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            
                SocketAsyncEventArgs acceptEventArg = new SocketAsyncEventArgs();
                acceptEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(acceptEventArg_Completed);

                if (!m_ListenSocket.AcceptAsync(acceptEventArg))
                    ProcessAccept(acceptEventArg);

                return true;

            }
            catch (Exception e)
            {
                OnError(e);
                return false;
            }
        }
Example #5
0
        private void SendQuery2(IPAddress ipAddress, int port)
        {
            int timeout = 5000;

            if (ipAddress == null)
            {
                throw new ArgumentNullException();
            }

            //preparing the DNS query packet.
            byte[] QueryPacket = MakeQuery();

            //opening the UDP socket at DNS server
            IPAddress serverAddress = ipAddress;
            EndPoint  endPoint      = new IPEndPoint(serverAddress, port);
            SOCKET    socket        = new SOCKET(serverAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp);

            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, timeout);
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, timeout);
            socket.SendTo(QueryPacket, endPoint);
            data = new byte[512];

            length = socket.ReceiveFrom(data, ref endPoint);

            //un pack the byte array & makes an array of resource record objects.
            ReadResponse();

            socket.Shutdown(SocketShutdown.Both);
        }
Example #6
0
        ///<summary>
        /// Starts listening to network notifications
        ///</summary>
        public void Start()
        {
            if (socket != null)
            {
                if (!IsStop) return;
                StartListening();
                IsStop = false;
                return;
            }
            IsStop = false;
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
            NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface adapter in adapters.Where(card => card.OperationalStatus == OperationalStatus.Up))
            {
                IPInterfaceProperties properties = adapter.GetIPProperties();
                foreach (var ipaddress in properties.UnicastAddresses.Where(x => x.Address.AddressFamily == AddressFamily.InterNetwork))
                {
                    socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, (object)new MulticastOption(IPAddress.Parse("224.0.0.1"), ipaddress.Address));
                }
            }

            socket.Bind(new IPEndPoint(IPAddress.Any, 12391));
            StartListening();
        }
Example #7
0
        public virtual void Listen(int port)
        {
            // Check if the server has been disposed.
            if (_disposed) throw new ObjectDisposedException(this.GetType().Name, "Server has been disposed.");

            // Check if the server is already listening.
            if (IsListening) throw new InvalidOperationException("Server is already listening.");

            // Create new TCP socket and set socket options.
            Listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try {
                // This is failing on Linux; dunno why.
                Listener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, true);
            } catch (SocketException e) {
                Logger.DebugException(e, "Listen");
            }
            Listener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);

            // Bind.
            Listener.Bind(new IPEndPoint(IPAddress.Any, port));
            this.Port = port;

            // Start listening for incoming connections.
            Listener.Listen(10);
            IsListening = true;

            // Begin accepting any incoming connections asynchronously.
            Listener.BeginAccept(AcceptCallback, null);
        }
Example #8
0
 public CSocket(IPEndPoint _endPoint, ScoketPool _pool, SocketPoolProfile config)
 {
     socketConfig = config;
     endpoint = _endPoint;
     pool = _pool;
     Socket _socket = new Socket(_endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
     _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, (int)config.SendTimeout.TotalMilliseconds);
     _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 24 * 3600 * 1000/*one day*/);//(int)config.ReceiveTimeout.TotalMilliseconds);
     _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, !config.Nagle);
     _socket.Connect(_endPoint);
     socket = _socket;
     this.inputStream = new BufferedStream(new NetworkStream(this.socket), config.BufferSize);
     Thread th = new Thread(delegate() {
         while (true)
         {
             try
             {
                 Receive();
             }
             catch (Exception ex)
             {
                 logger.Notice(ex.Message);
             }
         }
     });
     th.Start();
 }
Example #9
0
        /// <summary>
        /// 设置会话的心跳包
        /// </summary>
        /// <param name="socket">客户端</param>
        /// <param name="dueTime">延迟的时间量(以毫秒为单位)</param>
        /// <param name="period">时间间隔(以毫秒为单位)</param>
        /// <returns></returns>
        private bool TrySetKeepAlive(System.Net.Sockets.Socket socket, int dueTime, int period)
        {
            var inOptionValue  = new byte[12];
            var outOptionValue = new byte[12];

            ByteConverter.ToBytes(1, ByteConverter.Endian).CopyTo(inOptionValue, 0);
            ByteConverter.ToBytes(dueTime, ByteConverter.Endian).CopyTo(inOptionValue, 4);
            ByteConverter.ToBytes(period, ByteConverter.Endian).CopyTo(inOptionValue, 8);

            try
            {
                socket.IOControl(IOControlCode.KeepAliveValues, inOptionValue, outOptionValue);
                return(true);
            }
            catch (NotSupportedException)
            {
                socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, inOptionValue);
                return(true);
            }
            catch (NotImplementedException)
            {
                socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, inOptionValue);
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
        public static void SendWWTRemoteCommand(string targetIP, string command, string param)
        {
            Socket sockA = null;
            IPAddress target = null;
            sockA = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.IP);
            if(targetIP == "255.255.255.255")
            {
                sockA.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
                target = IPAddress.Broadcast;

            }
            else
            {
                target = IPAddress.Parse(targetIP);
            }

            IPEndPoint bindEPA = new IPEndPoint(IPAddress.Parse(NetControl.GetThisHostIP()), 8099);
            sockA.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
            sockA.Bind(bindEPA);

            EndPoint destinationEPA = (EndPoint)new IPEndPoint(target, 8089);

            string output = "WWTCONTROL2" + "," + Earth3d.MainWindow.Config.ClusterID + "," + command + "," + param;

            Byte[] header = Encoding.ASCII.GetBytes(output);

            sockA.SendTo(header, destinationEPA);
            sockA.Close();
        }
Example #11
0
        public PooledSocket(SocketPool socketPool, IPEndPoint endPoint, int sendReceiveTimeout, int connectTimeout)
        {
            this.socketPool = socketPool;
            Created = DateTime.Now;

            //Set up the socket.
            socket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, sendReceiveTimeout);
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, sendReceiveTimeout);
            socket.ReceiveTimeout = sendReceiveTimeout;
            socket.SendTimeout = sendReceiveTimeout;

            //Do not use Nagle's Algorithm
            socket.NoDelay = true;

            //Establish connection asynchronously to enable connect timeout.
            IAsyncResult result = socket.BeginConnect(endPoint, null, null);
            bool success = result.AsyncWaitHandle.WaitOne(connectTimeout, false);
            if (!success) {
                try { socket.Close(); } catch { }
                throw new SocketException();
            }
            socket.EndConnect(result);

            //Wraps two layers of streams around the socket for communication.
            stream = new BufferedStream(new NetworkStream(socket, false));
        }
        protected ISocketSession RegisterSession(Socket client, ISocketSession session)
        {
            if (m_SendTimeOut > 0)
                client.SendTimeout = m_SendTimeOut;

            if (m_ReceiveBufferSize > 0)
                client.ReceiveBufferSize = m_ReceiveBufferSize;

            if (m_SendBufferSize > 0)
                client.SendBufferSize = m_SendBufferSize;

            if(!Platform.SupportSocketIOControlByCodeEnum)
                client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
            else
                client.IOControl(IOControlCode.KeepAliveValues, m_KeepAliveOptionValues, null);

            client.NoDelay = true;
            client.UseOnlyOverlappedIO = true;
            client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);

            IAppSession appSession = this.AppServer.CreateAppSession(session);

            if (appSession == null)
                return null;

            return session;
        }
Example #13
0
        public void createClient(int coreManagerId)
        {
            try
            {
                byte[] commandBuffer = createConnection(coreManagerId);
                if (commandBuffer == null) return;
                Command resultCommand = AbstractCommand.deSerialize(commandBuilder, commandBuffer, 0, commandBuffer.Length);
                CommandStatus status = resultCommand.getStatus();
                if (!CommandStatus.success.Equals(status))
                {
                    throw new PlanckDBException(status, "Fail to create connection due to " + status.getMessage());
                }
                multicastSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                IPAddress ip = IPAddress.Parse(dbProperties.getMulticastIp());
                multicastSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip));
                multicastSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 2);
                IPEndPoint ipep = new IPEndPoint(ip, 4567);
                multicastSocket.Connect(ipep);
                //multicastSocket.setInterface(InetAddress.getByName(dbProperties.getNetworkInterface()));
                active = true;
                Thread thread = new Thread(new ThreadStart(run));
                thread.Start();
                Thread.Sleep(1000);
            }catch (PlanckDBException e){
                multicastConnectionHolder.handleMulticastConnectionFailure(this);
                throw e;

            }
            catch (Exception e)
            {
                multicastConnectionHolder.handleMulticastConnectionFailure(this);
                throw new PlanckDBException(CommandStatus.unsupported, "TCP connection failure due to IOException : " + e.Message);
            }
        }
        public async Task<bool> StartupAsync(string multicastIP, int multicastPort)
        {
            await ShutdownAsync();
            IsRunning = true;

            IPAddress serverIP;
            if (string.IsNullOrEmpty(multicastIP) || !IPAddress.TryParse(multicastIP, out serverIP))
            {
                await ShutdownAsync();
                return false;
            }

            socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);

            //Extrememly important to bind the socket BEFORE joing the multicast group
            socket.Bind(new IPEndPoint(IPAddress.Any, 11118));
            socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 1);
            socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(serverIP, IPAddress.Any));

            if (!BeginListening())
            {
                await ShutdownAsync();
                return false;
            }
            return true;
        }
Example #15
0
        public void Connect()
        {
            if (c == null) return;

            SocketPermission permission = new SocketPermission(System.Security.Permissions.PermissionState.Unrestricted);
            permission.Demand();

            IPHostEntry heserver = Dns.Resolve(c.XMLConf.Host);
            IPAddress iadd = (IPAddress)heserver.AddressList[0];
            IPEndPoint ip = new IPEndPoint(iadd, c.XMLConf.Port);

            s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
            s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.NoDelay, 1);
            s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.DontFragment, 1);

            while(!s.Connected)
            {
                try
                {
                    s.Connect(ip);
                }
                catch (Exception e)
                {
                    //MessageBox.Show("Verbindung fehlgeschlagen! "+e.Message);
                    c.use_network = false;
                    Thread.Sleep(1000);
                }
            }

            c.use_network = true;

            SendHelloToZusi(s);
        }
Example #16
0
        public void Start()
        {
            lock(runLock)
            {
                if(isRunning)
                {
                    return;
                }

                var ipEndPoint = new IPEndPoint(IPAddress.Any, Settings.Port);
                var listenEndPoint = (EndPoint) ipEndPoint;

                multicastSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                multicastSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                multicastSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, Settings.TimeToLive);
                multicastSocket.Bind(ipEndPoint);

                var multicastOption = new MulticastOption(Settings.MulticastGroupAddress, IPAddress.Any);
                multicastSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, multicastOption);

                var stateObject = new StateObject { Socket = multicastSocket };

                multicastSocket.BeginReceiveFrom(stateObject.Buffer, 0, stateObject.Buffer.Length, SocketFlags.None, ref listenEndPoint, OnReceiveSocketData, stateObject);

                isRunning = true;
            }
        }
Example #17
0
        private void createSockets()
        {
            IPAddress tmp_addr = null;

            tmp_addr   = Address.Resolve(Enclosing_Instance.discovery_addr);
            mcast_addr = new Address(tmp_addr, Enclosing_Instance.discovery_port);

            try
            {
                IPEndPoint sendEndPoint  = new IPEndPoint(mcast_addr.IpAddress, mcast_addr.Port);
                IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 0);

                mcast_send_sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                mcast_send_sock.Bind(localEndPoint);
                mcast_send_sock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(mcast_addr.IpAddress, IPAddress.Any));
                mcast_send_sock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, ip_ttl);
                mcast_send_sock.Connect(sendEndPoint);
            }
            catch (Exception ex)
            {
                throw ex;
            }

            setBufferSizes();
        }
        /// <summary>
        /// 启动监听
        /// </summary>
        /// <param name="config">服务器配置</param>
        /// <returns></returns>
        public override bool Start(IServerConfig config)
        {
            m_ListenSocket = new System.Net.Sockets.Socket(this.Info.EndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                //关联终结地
                m_ListenSocket.Bind(this.Info.EndPoint);
                //设置监听最大连接数
                m_ListenSocket.Listen(m_ListenBackLog);

                m_ListenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);

                m_ListenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
                //初始化套接字操作
                SocketAsyncEventArgs acceptEventArg = new SocketAsyncEventArgs();
                m_AcceptSAE = acceptEventArg;
                //定义一个连接完成事件
                acceptEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(acceptEventArg_Completed);
                if (!m_ListenSocket.AcceptAsync(acceptEventArg))
                {
                    ProcessAccept(acceptEventArg);
                }
                return true;
            }
            catch (Exception e)
            {
                OnError(e);
                return false;
            }
        }
Example #19
0
        public void SendServerPing()
        {
            StartListeningForServerPingBacks();

            // Create a socket udp ipv4 socket
            using (var sock = new Socket(AddressFamily.Unspecified, SocketType.Dgram, ProtocolType.Udp))
            {
                // Create our endpoint using the IP broadcast address and our port
            //                var endPoint = new IPEndPoint(IPAddress.Broadcast, ServiceInfo.UDPPort);
            //                var endPoint = new IPEndPoint(IPAddress.Parse("192.168.1.255"), ServiceInfo.UDPPort);
                var endPoint = new IPEndPoint(IPAddress.Parse("192.168.1.255"), 5353);

                // Serialize our ping "payload"
                //var data = Helpers.SerializeObject(new ServiceClientInfo(Helpers.GetCurrentIPAddress().ToString(), PORT));
                var data = Encoding.UTF8.GetBytes(String.Format("{0}:{1}", Helpers.GetCurrentIPAddress(), CLIENT_PORT));

                // Tell our socket to reuse the address so we can send and receive on the same port.
                sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

                // Tell the socket we want to broadcast - if we don't do this it won't let us send.
                sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);

                // Send the ping and close the socket.
                sock.SendTo(data, endPoint);
                sock.Close();
            }
        }
Example #20
0
        public IUdpSocket CreateUdpMulticastSocket(string ipAddress, int multicastTimeToLive, int localPort)
        {
            if (ipAddress == null) throw new ArgumentNullException("ipAddress");
            if (ipAddress.Length == 0) throw new ArgumentException("ipAddress cannot be an empty string.", "ipAddress");
            if (multicastTimeToLive <= 0) throw new ArgumentException("multicastTimeToLive cannot be zero or less.", "multicastTimeToLive");
            if (localPort < 0) throw new ArgumentException("localPort cannot be less than zero.", "localPort");

            var retVal = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            try
            {
                retVal.ExclusiveAddressUse = false;
                retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, multicastTimeToLive);
                retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse(ipAddress), _LocalIP));
                retVal.MulticastLoopback = true;

                return new UdpSocket(retVal, localPort, _LocalIP.ToString());
            }
            catch
            {
                if (retVal != null)
                    retVal.Dispose();

                throw;
            }
        }
Example #21
0
        public Client(Socket sock, ushort size)
        {
            try
            {
                Initialize();
                Items[0].SetBuffer(new byte[size], 0, size);

                _handle = sock;

                _handle.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
                _handle.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, true);
                _handle.NoDelay = true;

                BufferSize = size;
                _endPoint = (IPEndPoint)_handle.RemoteEndPoint;
                Connected = true;

                if (!_handle.ReceiveAsync(Items[0]))
                    Process(null, Items[0]);
            }
            catch
            {
                Disconnect();
            }
        }
Example #22
0
        public GDISendingChannel(GDIDeviceContext dc)
        {
            fFormatter = new BinaryFormatter();
            fMemoryStream = new MemoryStream(2048);

            fDeviceContext = dc;

            // Create the client
            fGDISpeaker = new UdpClient();

            // Create the broadcast socket
            IPAddress ip = IPAddress.Parse(GDIPortal.Multicast_Pixtour_Group);
            fBroadcastSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            fBroadcastSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip));
            fBroadcastSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 255);

            IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(GDIPortal.Multicast_Pixtour_Group), GDIPortal.Multicast_Pixtour_Port);
            fBroadcastSocket.Connect(ipep);


            // Setup the speaker
            fGraphPort = new GCDelegate(fDeviceContext.Resolution);
            fGraphPort.CommandPacked += new GCDelegate.DrawCommandProc(CommandPacked);


            // Setup the antennae to listen for commands
            fReceiver = new GDIReceivingChannel(GDIPortal.Multicast_Pixtour_Group, GDIPortal.Multicast_Pixtour_Port, fDeviceContext);
        }
        private void Initialize(IPEndPoint endpoint, Action<TcpStreamChannel> onClientAccepted)
        {
            if (endpoint == null)
            {
                throw new ArgumentNullException("endpoint");
            }
            if (onClientAccepted == null)
            {
                throw new ArgumentNullException("onClientConnected");
            }

            _onClientAcceptedAction = onClientAccepted;
            _listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _listenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
            _listenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
            _listenSocket.Bind(endpoint);
            _listenSocket.Listen(10);

            _acceptEventArg = new SocketAsyncEventArgs();
            _acceptEventArg.Completed += OnAcceptNewClient;

            if (!_listenSocket.AcceptAsync(_acceptEventArg))
            {
                OnAcceptNewClient(null, _acceptEventArg);
            }
        }
Example #24
0
 public LANGameManager(Game game, String name, String description, int maxDataSize = 1024,
     int ttl = 1, float introductionFrequency = 2, IPAddress multicastIpAddress = null)
     : base(game)
 {
     this.name = name;
     this.description = description;
     this.introFreq = introductionFrequency;
     this.incomingDataBuffer = new Byte[maxDataSize];
     // register us
     game.Services.AddService(typeof(LANGameManager), this);
     game.Components.Add(this);
     Registry.Register(this);
     // set up our broadcast communication
     multicastSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
         ProtocolType.Udp);
     if (multicastIpAddress != null)
     {
         multicastIpAddr = multicastIpAddress;
     }
     multicastSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership,
         new MulticastOption(multicastIpAddr));
     multicastSocket.SetSocketOption(SocketOptionLevel.IP,
         SocketOptionName.MulticastTimeToLive, ttl);
     multicastEndPoint = new IPEndPoint(multicastIpAddr, 4567);
     multicastSocket.Connect(multicastEndPoint);
 }
Example #25
0
        public CSocket(IPEndPoint _endPoint, SocketPool _pool, SocketPoolProfile config)
        {
            socketConfig = config;
            endpoint     = _endPoint;
            pool         = _pool;
            System.Net.Sockets.Socket _socket = new System.Net.Sockets.Socket(_endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, (int)config.SendTimeout.TotalMilliseconds);
            _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 24 * 3600 * 1000 /*one day*/);//(int)config.ReceiveTimeout.TotalMilliseconds);
            _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, !config.Nagle);
            _socket.Connect(_endPoint);
            socket           = _socket;
            this.inputStream = new BufferedStream(new NetworkStream(this.socket), config.BufferSize);
            Thread th = new Thread(delegate() {
                while (true)
                {
                    try
                    {
                        Receive();
                    }
                    catch (Exception ex)
                    {
                        logger.Notice(ex.Message);
                    }
                }
            });

            th.Start();
        }
 public NetworkClient()
 {
     Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     // Set our special Tcp hole punching socket options
     Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
     Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
     Buffer = new byte[1024];
 }
Example #27
0
 private void ConnectBroadcast()
 {
     broadcastSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
     broadcastSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership,
                                     new MulticastOption(broadcastAddress, IPAddress.Any));
     broadcastSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.ReuseAddress, 1);
     broadcastSocket.Connect(broadcastAddress, broadcastPort);
 }
        public void SetSoTimeout(int timeout)
        {
#if !CF && !SILVERLIGHT
            _delegate.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, timeout);
            _delegate.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, timeout);
#else
            _soTimeout = timeout;
#endif
        }
Example #29
0
        public void DetectAndStart()
        {
            var multicastEndPoint = new IPEndPoint(IPAddress.Parse("239.255.255.250"), 1900);
              var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
              socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
              socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership,
            new MulticastOption(multicastEndPoint.Address, IPAddress.Any));
              socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 80);
              socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastLoopback, true);
              socket.Bind(new IPEndPoint(IPAddress.Any, myMulticastListenPort++));

              Console.WriteLine("UDP-Socket setup done...\r\n");

              const string broadcastString =
            "M-SEARCH * HTTP/1.1\r\n" +
            "Host:239.255.255.250:1900\r\n" +
            "ST:urn:schemas-upnp-org:device:MediaRenderer:1\r\n" +
            "Man:\"ssdp:discover\"\r\n" +
            "MX:3\r\n" +
            "USER-AGENT: jonnyzzz\r\n" +
            "\r\n";

              myPool.EnqueueTask(() =>
              {
            bool gotResponse = false;
            var endTime = DateTime.Now + TimeSpan.FromSeconds(5);
            while (endTime > DateTime.Now)
            {
              if (socket.Available < 10)
              {
            Thread.Sleep(TimeSpan.FromMilliseconds(5));
            continue;
              }

              var buff = new byte[65536];
              var sz = socket.Receive(buff, SocketFlags.None);
              if (sz > 0)
              {
            myPool.EnqueueTask(() => ProcessResponse(buff, sz));
            gotResponse = true;
              }
            }

            if (!gotResponse)
            {
              Console.Out.WriteLine("No serivces were detected via UPNP. Retrying...");
              myPool.EnqueueTask(DetectAndStart);
            }

            Console.Out.WriteLine("M-Search completed");
              });

              Thread.Sleep(TimeSpan.FromMilliseconds(500));
              var message = Encoding.UTF8.GetBytes(broadcastString);
              socket.SendTo(message, SocketFlags.None, multicastEndPoint);
              Console.WriteLine("M-Search multicast sent...");
        }
Example #30
0
        internal override void Connect()
        {
            m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint remoteEP = new IPEndPoint(Dns.Resolve(this.EndPointUri.Host).AddressList[0], EndPointUri.Port);
            m_socket.Connect(remoteEP);

            m_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 60 * 1000);
            m_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 60 * 1000);
        }
        private Socket SetupSocket(Socket socket)
        {
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, Timeout);
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, Timeout);

            return socket;
        }
Example #32
0
        public void SAPProcessorThread()
        {
            // wait for the settings to be loaded...
            Socket MulticastSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, SAP_Port);
            IPAddress ip = IPAddress.Parse(SAP_IPAdress);

            MulticastSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.ReuseAddress, true);
            MulticastSocket.Bind(ipep);
            MulticastSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip, IPAddress.Any));

            #region we need some memory to store data withing
            byte[] receiveBuffer = new byte[2048];
            int receivedBufferLength = 0;
            #endregion

            // start the multicast client
            ConsoleOutputLogger.WriteLine("SAP / SDP Processor up and running...");

            bool done = false;
            Int32 ErrorCounter = 0;
            SDP_Processor sdp_processor = new SDP_Processor();

            while (!done)
            {
                // receive data
                receivedBufferLength = MulticastSocket.Receive(receiveBuffer);

                try
                {
                    //binary_recorder_writer.Write(receiveBuffer, 0, receivedBufferLength);
                    SDPPacket data = sdp_processor.ProcessSDP_Packet(receiveBuffer, receivedBufferLength);
                    ErrorCounter = 0;
                    //Console.WriteLine("Sender: " + data.Name);
                    //Console.WriteLine("IP: " + data.IP_Adress);
                    //Console.WriteLine("Port: " + data.Port);
                    //for (int i = 0; (i + epgPacketSize) <= receivedBufferLength; i += epgPacketSize) ProcessEPGPacket(receiveBuffer, i);
                }
                catch (Exception e)
                {
                    ConsoleOutputLogger.WriteLine("SAP / SDP Processor threw an error: " + e.Message);
                    ErrorCounter++;
                }
                // waiting FTW!!
                Thread.Sleep(10);

                // end this thread when 25 errors in a line occured
                if (ErrorCounter == 25)
                {
                    ConsoleOutputLogger.WriteLine("Too many errors in SAP / SDP Processor - shutting it down.");
                    youreDone();
                }
            }
            MulticastSocket.Close();
        }
Example #33
0
        public MemcachedSocket(IPEndPoint ip)
        {
            endpoint = ip;

            socket = new Socket(endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, (int)TimeSpan.FromSeconds(10).TotalMilliseconds);
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, (int)TimeSpan.FromSeconds(10).TotalMilliseconds);
            socket.NoDelay = true;
        }
Example #34
0
		///<summary>
		/// Starts listening to network notifications
		///</summary>
		public void Start()
		{
			socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
			socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
			socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership,
								   new MulticastOption(IPAddress.Parse("224.0.0.1"))); // all hosts group

			socket.Bind(new IPEndPoint(IPAddress.Any, 12391));
			StartListening();
		}
 public GasListener(string IP, int port)
 {
     m_ReadingBuf = new byte[2000];
     m_socketList = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
     m_socketList.Bind(new IPEndPoint(IPAddress.Any, port)); // локальная конечная точка
     m_socketList.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 10000);
     m_socketList.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse(IP), IPAddress.Any));
     m_ListenerThread = new Thread(ListenerTrend);
     m_ListenerThread.Start();
 }
Example #36
0
File: TCP.cs Project: cyberh0me/IoT
        private void ClientHandler(Socket cSocket)
        {
            Stream cStream;
            MemoryStream mStream;
            DateTime TimeOut;

            cSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, -2);
            cSocket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.KeepAlive, true);
            cSocket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);

            cStream = new NetworkStream(cSocket, true);
            PayloadType pType = PayloadType.Byte;
            mStream = new MemoryStream();
            TimeOut = DateTime.Now.AddMinutes(IDLE);

            while (DateTime.Compare(DateTime.Now, TimeOut) < 0 && _Shutdown == 0)
            {
                if (cSocket.Available != 0)
                {
                    TimeOut = DateTime.Now.AddMinutes(IDLE);

                    ReceiveData(ref cSocket, ref cStream, ref pType, ref mStream);

                    mStream.Position = 0;
                    if (mStream.Length > 0)
                    {
                        switch (pType)
                        {
                            case PayloadType.Boolean:
                                break;
                            case PayloadType.Byte:
                                byte b = (byte)mStream.ReadByte();
                                if (b == 0x01)
                                    PowerState.RebootDevice(true, 1000);
                                break;
                            case PayloadType.Bytes:
                                break;
                            case PayloadType.DateTime:
                                break;
                            case PayloadType.Guid:
                                break;
                            case PayloadType.String:
                                Debug.Print("received: " + mStream.ToArray().ToString(0, (int)mStream.Length));
                                byte[] payload = Encoding.UTF8.GetBytes("hello uwp");
                                cStream.Write(payload.Length.ToBytes(), 0, 4);
                                cStream.Write(payload, 0, payload.Length);
                                break;
                            default:
                                break;
                        }
                    }
                }
                Thread.Sleep(50);
            }
        }
Example #37
0
 public void setTcpNoDelay(bool b)
 {
     if (b)
     {
         sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, 1);
     }
     else
     {
         sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, 0);
     }
 }
Example #38
0
        public bool StartListening(AddressFamily family, int port, Func <IPEndPoint, INetworkConnection> getConMethod)
        {
            try
            {
                GetConnnection = getConMethod;
                if (Socket == null)
                {
                    Socket = new System.Net.Sockets.Socket(family, SocketType.Dgram, ProtocolType.Udp);
                    Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                    Socket.ExclusiveAddressUse = false;
                    if (family == AddressFamily.InterNetworkV6)
                    {
                        Socket.SetSocketOption(SocketOptionLevel.IPv6, (SocketOptionName)27, 0);     // set IPV6Only to false.  enables dual mode socket - V4+v6
                        Socket.Bind(new IPEndPoint(IPAddress.IPv6Any, port));
                    }
                    else
                    {
                        Socket.Bind(new IPEndPoint(IPAddress.Any, port));
                    }
                }
                Port = ((IPEndPoint)Socket.LocalEndPoint).Port;

                m_ListenArgs     = new byte[1024];
                m_ListenerThread = new Thread(new ThreadStart(DoListen));
                m_ListenerThread.IsBackground = true;
                m_ListenerThread.Name         = "UDPListenerSimplex Read Thread";

                m_State = new SockState(null, 1024, null);


                if (family == AddressFamily.InterNetworkV6)
                {
                    m_EndPoint = new IPEndPoint(IPAddress.IPv6Any, 0);
                }
                else
                {
                    m_EndPoint = new IPEndPoint(IPAddress.Any, 0);
                }

                m_ListenerThread.Start();
            }
            catch (Exception e)
            {
                Log.LogMsg("UDPListenerSimplex - error start listen: " + e.Message);
                return(false);
            }
            Listening = true;
            Log.LogMsg("UDPListenerSimplex - Listening for UDP traffic on port " + port.ToString());
            return(true);
        }
Example #39
0
        public bool StartReceiving(bool bBind)
        {
#if !MONO
            /// See http://blog.devstone.com/aaron/archive/2005/02/20/460.aspx
            /// This will stop winsock errors when receiving an ICMP packet
            /// "Destination unreachable"
            byte[] inValue  = new byte[] { 0, 0, 0, 0 };    // == false
            byte[] outValue = new byte[] { 0, 0, 0, 0 };    // initialize to 0
            s.IOControl(SIO_UDP_CONNRESET, inValue, outValue);
#endif

            if ((bBind == true) && (Bind() == false))
            {
                return(false);
            }

            lock (SyncRoot)
            {
                m_bReceive = true;
                s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, 128000);
                /// have 8 pending receives in the queue at all times

                DoReceive();
#if !MONO
                if (System.Environment.OSVersion.Version.Major >= 6)
                {
                    DoReceive();
                    DoReceive();
                }
#endif
            }
            return(true);
        }
Example #40
0
 /// <summary>
 /// 开启服务,连接服务端
 /// </summary>
 public void StartClient()
 {
     try
     {
         //1.0 实例化套接字(IP4寻址地址,流式传输,TCP协议)
         _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
         //2.0 创建IP对象
         IPAddress address = IPAddress.Parse(_ip);
         //3.0 创建网络端口包括ip和端口
         IPEndPoint endPoint = new IPEndPoint(address, _port);
         //4.0 建立连接
         _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
         _socket.Connect(endPoint);
         //Console.WriteLine("连接服务器成功");
         //5.0 接收数据
         int length = _socket.Receive(buffer);
         var t      = string.Format("接收服务器{0},消息:{1}", _socket.RemoteEndPoint.ToString(), Encoding.UTF8.GetString(buffer, 0, length));
         //6.0 像服务器发送消息
         for (int i = 0; i < 10; i++)
         {
             Thread.Sleep(2000);
             string sendMessage = string.Format("客户端发送的消息,当前时间{0}", DateTime.Now.ToString());
             _socket.Send(Encoding.UTF8.GetBytes(sendMessage));
             var tt = string.Format("像服务发送的消息:{0}", sendMessage);
         }
     }
     catch (Exception ex)
     {
         _socket.Shutdown(SocketShutdown.Both);
         _socket.Close();
         //Console.WriteLine(ex.Message);
     }
     //Console.WriteLine("发送消息结束");
     ///Console.ReadKey();
 }
Example #41
0
        internal PhysicalSocket()
        {
            _socket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            _socket.DontFragment = true;
            //_socket.Blocking = false;

            // To avoid : "An existing connection was forcibly closed by the remote host"
            uint IOC_IN            = 0x80000000;
            uint IOC_VENDOR        = 0x18000000;
            uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;

            _socket.IOControl((int)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null);

            // Setup a default Send/Rcv buffer size
            _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, 100 * 1024);
            _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, 1000 * 1024);
        }
Example #42
0
        public void Connect(SNS.AddressFamily addressFamily, string server, int port)
        {
            IPAddress  ip = GetServerIpAddress(addressFamily, server);
            IPEndPoint ep = new IPEndPoint(ip, port);

            //Console.WriteLine( "SocketClient - connecting to server [{0}] [{2}:{1}] ", server, port, ip.ToString()  ) ;

            _socket = new SNS.Socket(addressFamily, SNS.SocketType.Stream, SNS.ProtocolType.Tcp);
            _socket.Connect(ep);

            _connected = true;

            _socket.SetSocketOption(SNS.SocketOptionLevel.Socket, SNS.SocketOptionName.Linger, new SNS.LingerOption(false, 0));
            _socket.SetSocketOption(SNS.SocketOptionLevel.Socket, SNS.SocketOptionName.ReceiveBuffer, SocketConstants.SOCKET_MAX_TRANSFER_BYTES);
            _socket.SetSocketOption(SNS.SocketOptionLevel.Socket, SNS.SocketOptionName.SendBuffer, SocketConstants.SOCKET_MAX_TRANSFER_BYTES);
            _socket.SetSocketOption(SNS.SocketOptionLevel.Tcp, SNS.SocketOptionName.NoDelay, 1);
        }
Example #43
0
 protected void SetSocketOption(SocketOptionLevel level, SocketOptionName name, int val)
 {
     try
     {
         sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, val);
     }
     catch
     {
     }
 }
Example #44
0
        /// <summary>
        /// 启用keep-alive
        /// </summary>
        /// <param name="socket"></param>
        /// <param name="intervalStart"></param>
        /// <param name="retryInterval"></param>
        public static void EnableKeepAlive(this System.Net.Sockets.Socket socket, uint keepAliveTime, uint interval)
        {
            var size    = sizeof(uint);
            var inArray = new byte[size * 3];

            Array.Copy(BitConverter.GetBytes(1u), 0, inArray, 0, size);
            Array.Copy(BitConverter.GetBytes(keepAliveTime), 0, inArray, size, size);
            Array.Copy(BitConverter.GetBytes(interval), 0, inArray, size * 2, size);
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, inArray);
        }
Example #45
0
        private void createSockets()
        {
            IPAddress tmp_addr = null;

            tmp_addr   = Address.Resolve(Enclosing_Instance.discovery_addr);
            mcast_addr = new Address(tmp_addr, Enclosing_Instance.discovery_port);

            try
            {
                IPEndPoint recvEndPoint = new IPEndPoint(IPAddress.Any, mcast_addr.Port);
                mcast_recv_sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                mcast_recv_sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
                mcast_recv_sock.Bind(recvEndPoint);
                mcast_recv_sock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(mcast_addr.IpAddress, IPAddress.Any));
            }
            catch (Exception ex)
            {
                throw ex;
            }
            setBufferSizes();
        }
Example #46
0
        private void setBufferSizes()
        {
            if (mcast_recv_sock != null)
            {
                try
                {
                    mcast_recv_sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, buff_size);
                }
                catch (System.Exception ex)
                {
                    enclosingInstance.Stack.NCacheLog.Warn("failed setting mcast_send_buf_size in mcast_recv_sock: " + ex);
                }

                try
                {
                    mcast_recv_sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, buff_size);
                }
                catch (System.Exception ex)
                {
                    enclosingInstance.Stack.NCacheLog.Warn("failed setting mcast_recv_buf_size in mcast_recv_sock: " + ex);
                }
            }
        }
Example #47
0
        public Server Listen(int port, string host = null,
                             int backLog           = 128, Action listeningListener = null)
        {
            host = host ?? "0.0.0.0";

            if (listeningListener != null)
            {
                OnListening += listeningListener;
            }

            Core.EventLoop.Instance.Push(() =>
            {
                endPoint = new Wininet.IPEndPoint(
                    Wininet.IPAddress.IPv6Any,
                    port);

                Core.EventLoop.Instance.Push(() =>
                {
                    nativeSocket = new Winsock.Socket(
                        Winsock.AddressFamily.InterNetworkV6,
                        Winsock.SocketType.Stream,
                        Winsock.ProtocolType.Tcp);
                });
                Core.EventLoop.Instance.Push(() =>
                {
                    nativeSocket.SetSocketOption(
                        Winsock.SocketOptionLevel.IPv6,
                        Winsock.SocketOptionName.IPv6Only,
                        false);
                });
                Core.EventLoop.Instance.Push(() =>
                {
                    nativeSocket.Bind(endPoint);
                    nativeSocket.Listen(128);
                });

                if (OnListening != null)
                {
                    Core.EventLoop.Instance.Push(() =>
                    {
                        OnListening();
                    });
                }

                _acceptConnection();
            });

            return(this);
        }
        private SocketClient(string ipAdd, int port)
        {
            //_logger = LogManager.GetLogger(this.GetType());
            _bufferManager = new BufferManager(ChunkSize, ChunkSize);
            _bufferManager.InitBuffer();
            _messageHandler = new MessageHandler();

            //_bufferManager
            //    = new BufferManager(this.socketClientSettings.BufferSize * this.socketClientSettings.NumberOfSaeaForRecSend * this.socketClientSettings.OpsToPreAllocate,
            //                        this.socketClientSettings.BufferSize * this.socketClientSettings.OpsToPreAllocate);

            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1);
            _addr = new IPEndPoint(IPAddress.Parse(ipAdd), port);
        }
Example #49
0
        /// <summary>
        /// 启动监听的端口
        /// </summary>
        /// <param name="port">要监听的端口号</param>
        /// <param name="localaddr">要绑定的ip地址</param>
        /// <param name="reuseAddress">是否运行端口复用</param>
        public virtual void Start(int port, IPAddress localaddr = null, bool reuseAddress = true)
        {
            var serverSocketEP = new IPEndPoint(localaddr ?? IPAddress.Any, port);

            serverSocket = new Socket(serverSocketEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            if (reuseAddress)
            {
                //serverSocket.ExclusiveAddressUse = true;
                serverSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            }
            serverSocket.Bind(serverSocketEP);
            serverSocket.Listen(int.MaxValue);
            serverSocket.BeginAccept(AcceptSocketCallback, serverSocket);
            IsStart = true;
            WriteLog($"服务启动,监听IP:{serverSocketEP.Address},端口:{port}");
        }
Example #50
0
        protected sealed override async Task InternalOpenAsync(bool internalCall = false)
        {
            try
            {
                if (_shutdown || IsConnected)
                {
                    return;
                }
                await DisposeSocketAsync().ConfigureAwait(false);

                _identity = null;
                _socket   = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
                {
                    ReceiveBufferSize = _configuration.ReceiveBufferSize,
                    NoDelay           = true
                };
                _logger?.LogDebug("Socket connecting. ({0}:{1})", _config.Hostname, _config.ServiceName);
                await _socket.ConnectAsync(_config.Hostname, _config.ServiceName).ConfigureAwait(false);

                EnsureConnected();
                _logger?.LogDebug("Socket connected. ({0}:{1})", _config.Hostname, _config.ServiceName);
                if (_config.KeepAlive)
                {
                    _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1);
                }

                if (internalCall)
                {
                    EnableAutoReconnectReconnect();
                }

                _tokenSource   = new CancellationTokenSource();
                _receivingTask = Task.Factory.StartNew(() => StartReceive(), _tokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
                await PublishConnectionStateChanged(true).ConfigureAwait(false);
            }
            catch (Exception)
            {
                await DisposeSocketAsync();
                await HandleSocketDown().ConfigureAwait(false);

                if (!internalCall)
                {
                    throw;
                }
            }
        }
 public bool start(string addr, int port)
 {
     try
     {
         _udpForSend?.Dispose();
         _udpForSend = new UdpClient(0); // 送信元ポート0(未使用ポートが割当てられる)
         _addr       = addr;
         _port       = port;
         var socket = new System.Net.Sockets.Socket(SocketType.Dgram, ProtocolType.Udp);
         socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, 1024 * 1024);
         return(true);
     }
     catch
     {
         return(false);
     }
 }
Example #52
0
        /// <summary>
        /// 服务端连接
        /// </summary>
        public void Connect()
        {
            try
            {
                if (null != _Socket)
                {
                    _Socket.Dispose();
                }
                _Socket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //允许多个socket访问本地同一个IP和端口号
                _Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

                switch (this._WorkingMode)
                {
                case SocketMode.Server:
                    IPAddress  localIP = IPAddress.Parse(_LocalIP);
                    IPEndPoint ipl     = new IPEndPoint(localIP, _WorkingPort);
                    _Socket.Bind(ipl);
                    _Socket.Listen(10);
                    _Socket.BeginAccept(new AsyncCallback(_Accept), _Socket);
                    break;

                case SocketMode.Client:
                    _Socket.Connect(new IPEndPoint(IPAddress.Parse(_RemoteIP), _WorkingPort));
                    StateObject state = new StateObject();
                    _Socket.BeginReceive(state.buffer, 0, StateObject.BufferSize, SocketFlags.None, new AsyncCallback(_OnReceive), state);
                    break;

                default:
                    break;
                }
            }
            catch (Exception ex)
            {
                _Socket = null;
                //C_Error.WriteErrorLog("SeamTraking", ex);
                throw;
            }
        }
Example #53
0
 public IServer(int ID, string IPAddressString, int Port, string MySQLHostAddress, int MySQLHostPort, string[] MySQLAuthenticationDetails)
 {
     ServerID   = ID;
     PortNumber = Port;
     SetupManager();
     Socket = new Sockets.Socket(Sockets.AddressFamily.InterNetwork, Sockets.SocketType.Stream, Sockets.ProtocolType.Tcp);
     Socket.Bind(new System.Net.IPEndPoint(System.Net.IPAddress.Parse(IPAddressString), PortNumber));
     Socket.Listen(MaximumConnectionsQueue);
     Socket.SetSocketOption(Sockets.SocketOptionLevel.Socket, Sockets.SocketOptionName.KeepAlive, true);
     EnableIOCommunicationTunneling += new HandleIO(OnValidPacket);
     FireObject           += new HandleDisconnection(OnDisconnection);
     StatisticsUpdateTimer = new System.Timers.Timer(1000 * 240)
     {
         AutoReset = true
     };
     StatisticsUpdateTimer.Elapsed += UpdateStatistics;
     if (Database.Database.Init(MySQLHostAddress, MySQLHostPort, MySQLAuthenticationDetails))
     {
         Utils.Log.Info("MySQL", "A connection to the database has been made");
     }
     Utils.Log.Debug(ServerID.ToString(), "Amaryllis is running");
 }
Example #54
0
        public void Create()
        {
            foreach (var endpoint in _settings.IpEndpoint)
            {
                try
                {
                    var socket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);

                    socket.Bind(endpoint);
                    socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, 1);
                    var inBytes = new byte[] { 1, 0, 0, 0 };
                    socket.IOControl(IOControlCode.ReceiveAll, inBytes, null);

                    //todo catch exceptions -> iscreated = false if unable to handle exception
                    IsCreated = true;
                    _sockets.Add(socket);
                }
                catch
                {
                    // do not add it to the list
                }
            }
        }
Example #55
0
 /// <summary>
 /// 启动
 /// </summary>
 public void Start()
 {
     if (!IsRunning)
     {
         try
         {
             Init();  //初始化
             IsRunning = true;
             IPEndPoint localEndPoint = new IPEndPoint(Address, Port);
             // 创建监听socket
             _serverSocket = new System.Net.Sockets.Socket(localEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
             //_serverSock.ReceiveBufferSize = _bufferSize;
             //_serverSock.SendBufferSize = _bufferSize;
             if (localEndPoint.AddressFamily == AddressFamily.InterNetworkV6)
             {
                 // 配置监听socket为 dual-mode (IPv4 & IPv6)
                 // 27 is equivalent to IPV6_V6ONLY socket option in the winsock snippet below,
                 _serverSocket.SetSocketOption(SocketOptionLevel.IPv6, (SocketOptionName)27, false);
                 _serverSocket.Bind(new IPEndPoint(IPAddress.IPv6Any, localEndPoint.Port));
             }
             else
             {
                 _serverSocket.Bind(localEndPoint);
             }
             // 开始监听
             _serverSocket.Listen(this._maxClient);
             // 在监听Socket上投递一个接受请求。
             StartAccept(null);
         }
         catch (Exception e)
         {
             Console.WriteLine("Socket Server建立失败,错误为:" + e.Message);
             IsRunning = false;
         }
     }
 }
Example #56
0
        /// <summary>
        /// 启动监听的端口
        /// </summary>
        /// <param name="port">要监听的端口号</param>
        /// <param name="localaddr">要绑定的ip地址</param>
        /// <param name="reuseAddress">是否运行端口复用</param>
        public virtual void Start(int port, IPAddress localaddr = null, bool reuseAddress = true)
        {
            var serverSocketEP = new IPEndPoint(localaddr ?? IPAddress.Any, port);

            serverSocket = new Socket(serverSocketEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            if (reuseAddress)
            {
                //serverSocket.ExclusiveAddressUse = true;
                serverSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            }
            serverSocket.Bind(serverSocketEP);
            serverSocket.Listen(int.MaxValue);
            serverSocket.BeginAccept(AcceptSocketCallback, serverSocket);
            IsStart = true;
            WriteLog($"服务启动,监听IP:{serverSocketEP.Address},端口:{port}");

            timer.Elapsed += (o, e) =>
            {
                Console.Title = ($"当前客户端:{Clients.Length}个,每秒处理包:{count}个,总处理个数:{TotalCount}");
                count         = 0;
            };

            timer.Start();
        }
        //*********************************************
        //* Connect to the socket and begin listening
        //* for responses
        //********************************************
        private void Connect()
        {
            System.Net.IPEndPoint  endPoint = null;
            System.Net.IPHostEntry IP       = null;

            System.Net.IPAddress address = new System.Net.IPAddress(0);
            if (System.Net.IPAddress.TryParse(m_IPAddress, out address))
            {
                endPoint = new System.Net.IPEndPoint(address, m_Port);
            }
            else
            {
                try
                {
                    IP = System.Net.Dns.GetHostEntry(m_IPAddress);
                    //* Ethernet/IP uses port AF12 (44818)
                    endPoint = new System.Net.IPEndPoint(IP.AddressList[0], m_Port);
                }
                catch (Exception ex)
                {
                    throw new FormatException("Can't resolve the address " + m_IPAddress);
                    return;
                }
            }


            if (WorkSocket == null || !WorkSocket.Connected)
            {
                if (m_ProtocolType == System.Net.Sockets.ProtocolType.Tcp)
                {
                    WorkSocket = new System.Net.Sockets.Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                    //* Comment these out for Compact Framework
                    WorkSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 5000);
                    WorkSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
                }
                else
                {
                    WorkSocket = new System.Net.Sockets.Socket(endPoint.AddressFamily, SocketType.Dgram, m_ProtocolType);
                }

                WorkSocket.SendTimeout       = 2000;
                WorkSocket.ReceiveBufferSize = 0x5000;
            }

            try
            {
                try
                {
                    WorkSocket.Connect(endPoint);
                }
                catch (SocketException ex)
                {
                    //* Return an error code
                    OnComError("Could Not Connect to Server : " + ex.Message);

                    CloseConnection();
                    throw;
                }


                OnConnectionEstablished(System.EventArgs.Empty);

                StartTestThread();
            }
            catch (SocketException ex)
            {
                // 10035 == WSAEWOULDBLOCK
                if (ex.NativeErrorCode.Equals(10035))
                {
                    //Throw
                }
                else
                {
                    throw; //New Exception(m_IPAddress & " " & ex.Message)
                }
            }


            WorkSocket.Blocking = true;
            if (m_ProtocolType == System.Net.Sockets.ProtocolType.Tcp)
            {
                WorkSocket.LingerState = new System.Net.Sockets.LingerOption(true, 1000);
            }


            //* Don't buffer the data, so it goes out immediately
            //* Otherwise packets send really fast will get grouped
            //* And the PLC will not respond to all of them
            WorkSocket.SendBufferSize = 1;

            SocketStateObject so = new SocketStateObject();

            so.WorkSocket = WorkSocket;

            WorkSocket.BeginReceive(so.data, 0, so.data.Length, SocketFlags.None, DataReceivedCallback, so);
        }
Example #58
0
        public bool StartListening(AddressFamily family, int port, int maxSimultaneousListens, Func <IPEndPoint, INetworkConnection> getConMethod)
        {
            try
            {
                GetConnnection = getConMethod;
                if (Socket == null)
                {
                    //// Log.LogMsg("Testy 30");
                    Socket = new System.Net.Sockets.Socket(family, SocketType.Dgram, ProtocolType.Udp);
                    //// Log.LogMsg("Testy 31");
                    Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                    //// Log.LogMsg("Testy 32");
                    Socket.ExclusiveAddressUse = false;
                    //// Log.LogMsg("Testy 33");
                    if (family == AddressFamily.InterNetworkV6)
                    {
                        //// Log.LogMsg("Testy 34");
                        Socket.SetSocketOption(SocketOptionLevel.IPv6, (SocketOptionName)27, 0); // set IPV6Only to false.  enables dual mode socket - V4+v6
                        //// Log.LogMsg("Testy 35");
                        Socket.Bind(new IPEndPoint(IPAddress.IPv6Any, port));
                        //// Log.LogMsg("Testy 36");
                    }
                    else
                    {
                        //// Log.LogMsg("Testy 37");
                        Socket.Bind(new IPEndPoint(IPAddress.Any, port));
                    }
                }
                //// Log.LogMsg("Testy 38");
                Port = ((IPEndPoint)Socket.LocalEndPoint).Port;

                m_ListenArgs = new List <SocketAsyncEventArgs>(maxSimultaneousListens);
                for (int i = 0; i < maxSimultaneousListens; i++)
                {
                    //// Log.LogMsg("Testy 39");
                    SocketAsyncEventArgs arg = SocketAsyncEventArgsCache.PopReadEventArg(new EventHandler <SocketAsyncEventArgs>(ReadCompleted), Socket);
                    if (family == AddressFamily.InterNetworkV6)
                    {
                        arg.RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Any, 0);
                    }
                    else
                    {
                        arg.RemoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
                    }

                    //// Log.LogMsg("Testy 40");
                    m_ListenArgs.Add(arg);
                    //// Log.LogMsg("Testy 41");
                    bool willRaiseEvent = Socket.ReceiveFromAsync(arg);
                    //// Log.LogMsg("Testy 999");
                    if (!willRaiseEvent)
                    {
                        //// Log.LogMsg("Testy 42");
                        OnReceiveResolved(arg);
                    }
                }
            }
            catch (Exception e)
            {
                Log.LogMsg("UDPListener - error start listen: " + e.Message);
                return(false);
            }
            Listening = true;
            Log.LogMsg("UDPListener - Listening for UDP traffic on port " + port.ToString() + " with " + maxSimultaneousListens.ToString() + " max listeners.");
            return(true);
        }
Example #59
0
 void Utils.Wrappers.Interfaces.ISocket.SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, bool optionValue)
 {
     InternalSocket.SetSocketOption(optionLevel, optionName, optionValue);
 }
Example #60
0
 /// <summary>
 /// SimpleSocket的构造函数
 /// </summary>
 public SimpleSocket()
 {
     _socket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
     //_socket.Blocking = false; // ?
 }