Bind() public method

public Bind ( EndPoint localEP ) : void
localEP System.Net.EndPoint
return void
        public WebServer()
        {
            greenThread = new Thread(green.LightControl);
            greenThread.Start();
            amberThread = new Thread(amber.LightControl);
            amberThread.Start();
            redThread = new Thread(red.LightControl);
            redThread.Start();
            //Initialize Socket class
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            //Request and bind to an IP from DHCP server
            socket.Bind(new IPEndPoint(IPAddress.Any, 80));
            string address =
                Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0].IPAddress;
            //Debug print our IP address
            while (address == "192.168.5.100")
            {
                address =
                Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0].IPAddress;
                Thread.Sleep(2000);
            }
            Debug.Print(address);
            //Start listen for web requests
            socket.Listen(10);

            ListenForRequest();
        }
        private static void Server()
        {
            list = new List<IPAddress>();
            const ushort data_size = 0x400; // = 1024
            byte[] data;
            while (ServerRun)
            {
                Socket sock = new Socket(AddressFamily.InterNetwork,
                          SocketType.Dgram, ProtocolType.Udp);
                IPEndPoint iep = new IPEndPoint(IPAddress.Any, BroadcastRecievePort);
                try
                {
                    sock.Bind(iep);
                    EndPoint ep = (EndPoint)iep;

                    data = new byte[data_size];
                    if (!ServerRun) break;
                    int recv = sock.ReceiveFrom(data, ref ep);
                    string stringData = System.Text.Encoding.ASCII.GetString(data, 0, recv);
                    if (!list.Contains(IPAddress.Parse(ep.ToString().Split(':')[0])))
                        list.Add(IPAddress.Parse(ep.ToString().Split(':')[0]));

                    data = new byte[data_size];
                    if (!ServerRun) break;
                    recv = sock.ReceiveFrom(data, ref ep);
                    stringData = System.Text.Encoding.ASCII.GetString(data, 0, recv);
                    if (!list.Contains(IPAddress.Parse(ep.ToString().Split(':')[0])))
                        list.Add(IPAddress.Parse(ep.ToString().Split(':')[0]));

                    sock.Close();
                }
                catch { }
            }
        }
Example #3
1
        public server_socket( Object name, int port )
            : base()
        {
            try {
            /* 	    _server_socket = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp ); */
            /* 	    _server_socket.Bind( new IPEndPoint( 0, port ) );          */

            IPEndPoint endpoint;

            if( name != bigloo.foreign.BFALSE ) {
               String server = bigloo.foreign.newstring( name );
               IPHostEntry host = Dns.Resolve(server);
               IPAddress address = host.AddressList[0];
               endpoint = new IPEndPoint(address, port);
            } else {
               endpoint = new IPEndPoint( 0, port );
            }

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

            _server_socket.Listen( 10 );
             }
             catch (Exception e) {
            socket_error( "make-server-socket",
              "cannot create socket (" + e.Message + ")",
              new bint( port ) );
             }
        }
 protected override void RecieveCallback(IAsyncResult Result)
 {
     DatagramState Dstate = (DatagramState)Result.AsyncState;
     int bytes = 0;
     Socket S = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
     S.Bind(new IPEndPoint(IPAddress.Any, 0));
     Socket past = Dstate.ClientSocket;
     Dstate.ClientSocket = S;
     try
     {
         bytes = past.EndReceiveFrom(Result, ref Dstate.EndPoint);
     }
     catch (Exception e)
     {
         Next.Set();
         Send("Respect the buffer size which is " + DatagramState.BufferSize.ToString(), Dstate);
         return;
     }
     if (bytes>0)
     {
         string content = "";
         Dstate.MsgBuilder.Append(Encoding.ASCII.GetString(Dstate.Buffer, 0, bytes));
         content = Dstate.MsgBuilder.ToString();
         Next.Set();
         try
         {
             string r = Calculate(content).ToString();
             Send(r, Dstate);
         }
         catch (Exception e)
         {
             Send(e.Message, Dstate);
         }
     }
 }
        public Http2SocketServer(Func<IDictionary<string, object>, Task> next, IDictionary<string, object> properties)
        {
            _next = next;
            _socket = new Socket(SocketType.Stream, ProtocolType.Tcp); // Dual mode

            IList<IDictionary<string, object>> addresses = 
                (IList<IDictionary<string, object>>)properties[OwinConstants.CommonKeys.Addresses];

            IDictionary<string, object> address = addresses.First();
            _enableSsl = !string.Equals((address.Get<string>("scheme") ?? "http"), "http", StringComparison.OrdinalIgnoreCase);

            _port = Int32.Parse(address.Get<string>("port") ?? (_enableSsl ? "443" : "80"), CultureInfo.InvariantCulture);

            string host = address.Get<string>("host");
            if (string.IsNullOrWhiteSpace(host) || !host.Equals("*") || !host.Equals("+"))
            {
                _socket.Bind(new IPEndPoint(IPAddress.IPv6Any, _port));
            }
            else
            {
                _socket.Bind(new IPEndPoint(Dns.GetHostAddresses(host)[0], _port));
            }

            Listen();
        }
 internal DccListener(DccClient client, TimeSpan timeout, int port)
 {
     m_client = client;
     m_timeout = timeout;
     m_Port = port;
     m_closed = false;
     m_sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     try
     {
         try
         {
             m_sock.Bind(new IPEndPoint(Util.ExternalAddress, m_Port));
         }
         catch
         {
             m_sock.Bind(new IPEndPoint(Util.LocalHostAddress, m_Port));
         }
         m_sock.Listen(1);
         m_sock.BeginAccept(new AsyncCallback(OnAccept), null);
     }
     catch (Exception ex)
     {
         m_client.Dcc.ListenerFailedNotify(this, ex);
     }
     m_timeoutTimer = new Timer(m_timeout.TotalMilliseconds);
     m_timeoutTimer.Elapsed += OnTimeout;
     m_timeoutTimer.Start();
 }
Example #7
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 #8
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 #9
0
        static ManagmentService()
        {
            ClientList = new List<IncomingClient>();

            AppSettingsReader _settingsReader = new AppSettingsReader();

            string value = _settingsReader.GetValue("ServerRunAtIP", type: typeof(string)) as string;

            if (!IPAddress.TryParse(value, out ServerIP))
                throw new Exception(message: "Appseting ServerRunAtIP Error");

            value = _settingsReader.GetValue("ServerRunAtPort", type: typeof(string)) as string;

            if (!int.TryParse(value, out ServerPort))
                throw new Exception(message: "Appseting ServerRunAtPort Error");

            value = _settingsReader.GetValue("MaxPoolClient", type: typeof(string)) as string;

            if (!int.TryParse(value, out MaxClient))
                throw new Exception(message: "Appseting MaxPoolClient Error");

            ServerEndPoint = new IPEndPoint(ServerIP, ServerPort);

            ServerLisenerSocket = new Socket(addressFamily: AddressFamily.InterNetwork, socketType: SocketType.Stream, protocolType: ProtocolType.Tcp);

            ServerLisenerSocket.Bind(ServerEndPoint);
        }
Example #10
0
        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                //We are using TCP sockets
                serverSocket = new Socket(AddressFamily.InterNetwork,
                                          SocketType.Stream,
                                          ProtocolType.Tcp);

                //Assign the any IP of the machine and listen on port number 1000
                IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, 1000);

                //Bind and listen on the given address
                serverSocket.Bind(ipEndPoint);
                serverSocket.Listen(4);

                //Accept the incoming clients
                serverSocket.BeginAccept(new AsyncCallback(OnAccept), null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "SGSserverTCP",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Example #11
0
        static void Main(string[] args)
        {
            //1.创建socket
            Socket tpcServer = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);

            //2.绑定ip跟端口号 192.168.1.105
            IPAddress ipaddress = new IPAddress(new byte[]{192,168,1,105});
            EndPoint point = new IPEndPoint(ipaddress,7788);//ipendpoint 是对ip + 端口做了一层封装的类
            tpcServer.Bind(point); //向操作系统申请一个可用的ip跟端口号 用来做通信

            //3.开始监听 (等待客户端连接)
            tpcServer.Listen(100); //参数是最大连接数
            Console.WriteLine("开始监听");

            Socket clientSocket = tpcServer.Accept(); //暂停当前的线程,直到有一个客户端连接过来,之后进行下面的代码
            //使用返回的socket跟客户端做通信
            Console.WriteLine("客户端连接过来了");
            string message = "hello 欢迎你 ";
            byte[] data = Encoding.UTF8.GetBytes(message);//对字符串做编码,得到一个字符串的字节数组
            clientSocket.Send(data);
            Console.WriteLine("向客户端发送数据");

            byte[] data2 = new byte[1024]; //创建一个字节数组用来做容器,去承接客户端发送过来的数据
            int length = clientSocket.Receive(data2);
            string message2 = Encoding.UTF8.GetString(data2, 0, length);// 把字节数转化成一个字符串
            Console.WriteLine("接收到了一个从客户端发送过来的消息");

            Console.WriteLine(message2);

            Console.ReadKey();
        }
        internal void Bind()
        {
            if (_listenSocket != null)
            {
                throw new InvalidOperationException("Transport is already bound.");
            }

            System.Net.Sockets.Socket listenSocket;

            // Unix domain sockets are unspecified
            var protocolType = EndPoint is UnixDomainSocketEndPoint ? ProtocolType.Unspecified : ProtocolType.Tcp;

            listenSocket = new System.Net.Sockets.Socket(EndPoint.AddressFamily, SocketType.Stream, protocolType);

            // Kestrel expects IPv6Any to bind to both IPv6 and IPv4
            if (EndPoint is IPEndPoint ip && ip.Address == IPAddress.IPv6Any)
            {
                listenSocket.DualMode = true;
            }

            try {
                listenSocket.Bind(EndPoint);
            } catch (SocketException e) when(e.SocketErrorCode == SocketError.AddressAlreadyInUse)
            {
                throw new AddressInUseException(e.Message, e);
            }

            EndPoint = listenSocket.LocalEndPoint;

            listenSocket.Listen(512);

            _listenSocket = listenSocket;
        }
        public void Start(IPAddress address, int?port)
        {
            var localEndPoint = new IPEndPoint(address, port.HasValue ? port.Value : DEFAULT_PORT);

            _socket = new System.Net.Sockets.Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                _socket.Bind(localEndPoint);
                _socket.Listen(BACKLOG);

                Console.WriteLine("Server started. Listening to TCP clients at {0}:{1}", address.ToString(), localEndPoint.Port);

                while (true)
                {
                    _event.Reset();
                    _socket.BeginAccept(new AsyncCallback(AcceptCallback), this);
                    Console.WriteLine("Waiting for a connection...");
                    _event.WaitOne();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Example #14
0
        public void OpenChannel()
        {
            var logger = _loggerFactory.CreateLogger($"OpenChannel");

            _listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _listenSocket.Bind(new IPEndPoint(IPAddress.Loopback, _port));
            _listenSocket.Listen(10);

            logger.LogInformation($"Process ID {Process.GetCurrentProcess().Id}");
            logger.LogInformation($"Listening on port {_port}");

            while (true)
            {
                var acceptSocket = _listenSocket.Accept();
                logger.LogInformation($"Client accepted {acceptSocket.LocalEndPoint}");

                var connection = new ConnectionContext(acceptSocket,
                                                       _hostName,
                                                       _protocolManager,
                                                       _workspaceContext,
                                                       _projects,
                                                       _loggerFactory);

                connection.QueueStart();
            }
        }
Example #15
0
        public bool Bind()
        {
            if (m_bIsBound == true)
            {
                return(true);
            }

            lock (SyncRoot)
            {
                m_bReceive = true;
                System.Net.EndPoint epBind = (EndPoint)m_ipEp;
                try
                {
                    s.Bind(epBind);
                }
                catch (SocketException e3) /// winso
                {
                    LogError(MessageImportance.High, "EXCEPTION", string.Format("{0} - {1}", e3.ErrorCode, e3.ToString()));
                    return(false);
                }
                catch (ObjectDisposedException e4) // socket was closed
                {
                    LogError(MessageImportance.High, "EXCEPTION", e4.ToString());
                    return(false);
                }

                m_bIsBound = true;
            }

            return(true);
        }
Example #16
0
        public bool Start(string host, int port, int backlog)
        {
            IPAddress address;

            if (host == "0.0.0.0")
            {
                address = IPAddress.Any;
            }
            else
            {
                address = IPAddress.Parse(host);
            }
            IPEndPoint endpoint = new IPEndPoint(address, port);


            if (_listenSocket != null)
            {
                _listenSocket.Close();
                _listenSocket = null;
            }

            _listenSocket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            _listenSocket.Bind(endpoint);
            _listenSocket.Listen(backlog);
            _listenThread.Start();

            return(true);
        }
Example #17
0
        public ServerSocket(IPAddress IP, int Port)
        {
            RawSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            RawSocket.Bind(new IPEndPoint(IP, Port));

            Instance = this;
        }
        internal void Bind()
        {
            if (_listenSocket != null)
            {
                throw new InvalidOperationException("Transport already bound");
            }

            var listenSocket = new System.Net.Sockets.Socket(EndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            listenSocket.EnableFastPath();

            // Kestrel expects IPv6Any to bind to both IPv6 and IPv4
            if (EndPoint is IPEndPoint ip && ip.Address == IPAddress.IPv6Any)
            {
                listenSocket.DualMode = true;
            }

            try
            {
                listenSocket.Bind(EndPoint);
            }
            catch (SocketException e) when(e.SocketErrorCode == SocketError.AddressAlreadyInUse)
            {
                throw new AddressInUseException(e.Message, e);
            }

            EndPoint = listenSocket.LocalEndPoint;

            listenSocket.Listen(512);

            _listenSocket = listenSocket;
        }
        public override void Start()
        {
            if (!Disposed)
            {
                FSocket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                FSocket.Bind(LocalEndPoint);
                FSocket.Listen(FBackLog * FAcceptThreads);

                //----- Begin accept new connections!
                int loopCount          = 0;
                SocketAsyncEventArgs e = null;

                for (int i = 1; i <= FAcceptThreads; i++)
                {
                    e            = new SocketAsyncEventArgs();
                    e.UserToken  = this;
                    e.Completed += new EventHandler <SocketAsyncEventArgs>(BeginAcceptCallbackAsync);

                    if (!FSocket.AcceptAsync(e))
                    {
                        BeginAcceptCallbackAsync(this, e);
                    }
                    ;

                    ThreadEx.LoopSleep(ref loopCount);
                }
            }
        }
Example #20
0
        public EndPointListener(
            IPAddress address, int port, bool secure, string certFolderPath, X509Certificate2 defaultCert)
        {
            if (secure)
            {
                _secure = secure;
                _cert   = getCertificate(port, certFolderPath, defaultCert);
                if (_cert == null)
                {
                    throw new ArgumentException("No server certificate found.");
                }
            }

            _endpoint     = new IPEndPoint(address, port);
            _prefixes     = new Dictionary <ListenerPrefix, HttpListener> ();
            _unregistered = new Dictionary <HttpConnection, HttpConnection> ();

            _socket = new System.Net.Sockets.Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            _socket.Bind(_endpoint);
            _socket.Listen(500);

            var args = new SocketAsyncEventArgs();

            args.UserToken  = this;
            args.Completed += onAccept;
            _socket.AcceptAsync(args);
        }
Example #21
0
        private void OnClientConnect(IAsyncResult AcceptAsync)
        {
            try
            {
                Socket Sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                Sock = ListenerSock.EndAccept(AcceptAsync);
                Server ServerSock = new Server(Sock);
                //RaiseEvent if event is linked
                if (Connected != null)
                {
                    Connected(ServerSock);
                }
            }
            catch
            {

            }
            finally
            {
                ListenerSock.Dispose();
                ListenerSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                IPAddress hostIP = (Dns.Resolve(IPAddress.Any.ToString())).AddressList[0];
                ListenerSock.Bind(new IPEndPoint(hostIP, m_Port));
                ListenerSock.Listen(0);
                ListenerSock.BeginAccept(new AsyncCallback(OnClientConnect), null);
            }
        }
Example #22
0
        //ToDo faire l'ipv6 (dans loooongtemps)
        public SendRawPing()
        {
            dataSize = 256;
            ttlValue = 12;
            protocolHeaderList = new ArrayList();

            pingSocket = new Socket( AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp );
            pingSocket.SetSocketOption( SocketOptionLevel.IP, SocketOptionName.IpTimeToLive, ttlValue );

            IPEndPoint localEndPoint = new IPEndPoint( IPAddress.Any, 0 );
            pingSocket.Bind( localEndPoint );

            icmpHeader = new IcmpHeader();

            icmpHeader.Id = 0;
            icmpHeader.Sequence = 1;
            icmpHeader.Type = IcmpHeader.EchoRequestType;
            icmpHeader.Code = IcmpHeader.EchoRequestCode;

            protocolHeaderList.Add( icmpHeader );

            pingPayload = new byte[dataSize];
            for( int i = 0 ; i < pingPayload.Length ; i++ )
            {
                pingPayload[i] = (byte)'e';
            }

            pingPacket = icmpHeader.BuildPacket( protocolHeaderList, pingPayload );

            receiveBuffer = new byte[pingPacket.Length];
        }
Example #23
0
 public SocketManager(
     ILogger logger,
     IOptions <SocketOptions> options)
 {
     foreach (var socketAddress in options.Value.SocketAddresses)
     {
         var ipAddress  = IPAddress.Parse(socketAddress.HostName);
         var ipEndPoint = new IPEndPoint(ipAddress, socketAddress.Port);
         //创建服务器Socket对象,并设置相关属性
         var socket = new System.Net.Sockets.Socket(
             socketAddress.AddressFamily,
             socketAddress.SocketType,
             socketAddress.ProtocolType
             );
         //绑定ip和端口
         socket.Bind(ipEndPoint);
         //设置最长的连接请求队列长度
         socket.Listen(socketAddress.MaxBacklog);
         var clientSocket = new SocketClient()
         {
             Socket        = socket,
             SocketAddress = socketAddress
         };
         SocketClients.Enqueue(clientSocket);
         logger.LogInformation($"Socket:" +
                               $"{socketAddress.FullName} " +
                               $"{socketAddress.HostName}:" +
                               $"{socketAddress.Port} 注册监听成功");
     }
 }
Example #24
0
 public static ServerMock CreateTcp( int port, int bufferSize )
 {
     Socket socket = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
     socket.Bind( new IPEndPoint( IPAddress.Loopback, port ) );
     socket.Listen( 16 );
     return new ServerMock( socket, bufferSize );
 }
Example #25
0
        void connect()
        {
            CLientList = new List <System.Net.Sockets.Socket>();
            //ip la dia chi cua server.
            IP     = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 9999);
            server = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, SocketType.Stream, System.Net.Sockets.ProtocolType.IP);
            server.Bind(IP);
            System.Threading.Thread Listen = new System.Threading.Thread(() => {
                try
                {
                    while (true)
                    {
                        server.Listen(100);
                        Socket client = server.Accept();
                        CLientList.Add(client);

                        System.Threading.Thread receive1 = new System.Threading.Thread(Receive);
                        receive1.IsBackground            = true;
                        receive1.Start(client);
                    }
                }
                catch
                {
                    IP     = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 9999);
                    server = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, SocketType.Stream, System.Net.Sockets.ProtocolType.IP);
                }
            });
            Listen.IsBackground = true;
            Listen.Start();
        }
Example #26
0
        static void Main(string[] args)
        {
            Socket tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            string StrIp = "192.168.2.72";

            // 绑定ip.
            tcpServer.Bind(new IPEndPoint(IPAddress.Parse(StrIp), 7788));

            // 线程?
            tcpServer.Listen(100);

            Console.WriteLine("Server running..");

            // 死循环?
            while (true)
            {
                Socket clientSocket = tcpServer.Accept();

                Console.WriteLine("A client is connected!");

                // 把与每个客户端通信的逻辑.(收发消息.) 放到client端里做处理.
                Client client = new Client(clientSocket);

                clientList.Add(client);
            }
        }
Example #27
0
    public void LetListen()
    {
        ListenButton.Sensitive = false;

        IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 8000);

        g_listener = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        try
        {
            g_listener.Bind(localEndPoint);
            g_listener.Listen(100);

            var args = new SocketAsyncEventArgs();
            args.Completed += OnAccepted;
            StartAccept(args);

            Log("Listening has been started");
        }
        catch (SocketException se)
        {
            Log((string.Format("StartListening [SocketException] Error : {0} ", se.Message.ToString())));
        }
        catch (Exception ex)
        {
            Log((string.Format("StartListening [Exception] Error : {0} ", ex.Message.ToString())));
        }
    }
Example #28
0
        public static string StartListen(string IPadress, string portStr)
        {
            try
            {
                IPAddress ipAddress = IPAddress.Parse(IPadress);

                int port = System.Convert.ToInt32(portStr);

                m_mainSocket = new  System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream,
                                                              ProtocolType.Tcp);
                IPEndPoint ipLocal = new IPEndPoint(ipAddress, port);                //(IPAddress.Any, port);

                m_mainSocket.Bind(ipLocal);

                m_mainSocket.Listen(4);

                m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
                isRunning = true;
                return(ipLocal.ToString());
            }
            catch (SocketException se)
            {
                Console.WriteLine(se.Message);
                return(null);
            }
        }
Example #29
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();
        }
Example #30
0
        static void socket()
        {
            // (1) 소켓 객체 생성 (TCP 소켓)
            System.Net.Sockets.Socket sock = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // (2) 포트에 바인드
            IPEndPoint ep = new IPEndPoint(IPAddress.Any, 7000);

            sock.Bind(ep);

            // (3) 포트 Listening 시작
            sock.Listen(10);

            // (4) 연결을 받아들여 새 소켓 생성 (하나의 연결만 받아들임)
            System.Net.Sockets.Socket clientSock = sock.Accept();

            byte[] buff = new byte[8192];
            while (!Console.KeyAvailable) // 키 누르면 종료
            {
                // (5) 소켓 수신
                int n = clientSock.Receive(buff);

                string data = Encoding.UTF8.GetString(buff, 0, n);
                Console.WriteLine(data);

                // (6) 소켓 송신
                clientSock.Send(buff, 0, n, SocketFlags.None);  // echo
            }

            // (7) 소켓 닫기
            clientSock.Close();
            sock.Close();
        }
Example #31
0
        public bool Start()
        {
            try
            {
                if (_stopThreads)
                {
                    _stopThreads = false;

                    _thdWorker = new Thread(new ThreadStart(RemoveWorkerThreads));

                    _thdWorker.Start();

                    _listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                    // TODO: check if there is already a binding for the IPEndPoint
                    _listenSocket.Bind(new IPEndPoint(_address, _port));
                    _listenSocket.Listen(30);

                    _thdListener = new Thread(new ThreadStart(ListenerThread));

                    _thdListener.Start();
                }
            }
            catch (Exception)
            {
                Stop();
                return(false);
            }

            return(true);
        }
        /// <summary>
        /// Creates an NeonMika.Webserver instance
        /// </summary>
        /// <param name="portNumber">The port to listen for incoming requests</param>
        public Server(int portNumber = 80, bool DhcpEnable = true, string ipAddress = "", string subnetMask = "", string gatewayAddress = "")
        {
            var interf = NetworkInterface.GetAllNetworkInterfaces()[0];

            if (DhcpEnable)
            {
                //Dynamic IP
                interf.EnableDhcp();
                //interf.RenewDhcpLease( );
            }
            else
            {
                //Static IP
                interf.EnableStaticIP(ipAddress, subnetMask, gatewayAddress);
            }

            Debug.Print("Webserver is running on " + interf.IPAddress + " /// DHCP: " + interf.IsDhcpEnabled);

            this._PortNumber = portNumber;

            ResponseListInitialize();

            _ListeningSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _ListeningSocket.Bind(new IPEndPoint(IPAddress.Any, portNumber));
            _ListeningSocket.Listen(4);
        }
        /// <summary>
        /// Function :
        ///     Udp Local EndPoint Connect to Remote EndPoint
        /// </summary>
        public FunctionResult UdpConnectLocalToRemote()
        {
            UdpConnectRemoteSocket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            UdpConnectRemoteSocket.Bind(UdpConnectRemoteEndPoint);

            return(FunctionResult.Success);
        }
Example #34
0
        private void bomba1_DoWork(object sender, DoWorkEventArgs e)
        {
            Socket listener = new Socket(
                AddressFamily.InterNetwork,
                SocketType.Stream,
                ProtocolType.Tcp
            );

            String data = null;

            listener.Bind(bomba1EndPoint);
            listener.Listen(1);

            // Create the state object.
            sBomba1 = new StateObject();
            sBomba1.bomba = bomba1;
            sBomba1.workSocket = listener;

            while (true)
            {
                listener.Accept();
                bomba1Status.Text = "Bomba 1 conectada";

                while (true)
                {
                    int bytesRec = listener.Receive(sBomba1.buffer);
                    data += Encoding.ASCII.GetString(sBomba1.buffer, 0, bytesRec);
                    bomba1.ReportProgress(1, sBomba1);
                }
            }
        }
        /// <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 #36
0
        private void Listening()
        {
            IPAddress ServerIp = GetServerIP();
            int port =NetOperator.clientPort;
            IPEndPoint iep = new IPEndPoint(ServerIp, port);
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            byte[] byteMessage;
            socket.Bind(iep);
            while (true)
            {
                try
                {
                    socket.Listen(5);
                    Socket newSocket = socket.Accept();
                    byteMessage = new byte[newSocket.Available];
                    newSocket.Receive(byteMessage);

                    //mainProcess._globalMsgList;
                    //processMsg(byteMessage);
                }
                catch (SocketException ex)
                {

                }
            }
        }
Example #37
0
 private string GetRightIp()
 {
     try
     {
         using (var s = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
         {
             s.Bind(new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0));
             s.Connect("google.com", 0);
             var ipaddr = s.LocalEndPoint as System.Net.IPEndPoint;
             return(ipaddr.Address.ToString());
         }
     }
     catch (Exception ex)
     {
         var host = Dns.GetHostEntry(Dns.GetHostName());
         foreach (var ip in host.AddressList)
         {
             if (ip.AddressFamily == AddressFamily.InterNetwork)
             {
                 return(ip.ToString());
             }
         }
         throw new Exception("No network adapters with an IPv4 address in the system!");
     }
 }
Example #38
0
        static void Main(string[] args)
        {
            var listener = new Socket(
                AddressFamily.InterNetwork,
                SocketType.Stream,
                ProtocolType.Tcp);

            var ip = IPAddress.Parse("127.0.0.1");
            var ep = new IPEndPoint(ip, 8000);

            listener.Bind(ep);
            listener.Listen(1);

            for (; ; )
            {
                Console.WriteLine("接続待機中...");
                Socket connection = listener.Accept();

                // Accepted
                Console.WriteLine("Accepted!!");
                IPEndPoint remoteEP = (IPEndPoint)connection.RemoteEndPoint;
                Console.WriteLine("Remote IP = {0}", remoteEP.Address);
                Console.WriteLine("Remote Port = {0}", remoteEP.Port);

                // Receive
                byte[] receiveData = new byte[1000];
                int size = connection.Receive(receiveData);
                string receiveString = Encoding.UTF8.GetString(receiveData, 0, size);
                Console.WriteLine("受信完了!");
                Console.WriteLine("受信文字列 = {0}\n", receiveString);

            }
        }
        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 #40
0
 /// <summary>
 /// 绑定终结点
 /// </summary>
 /// <param name="socket">Socket对象</param>
 /// <param name="endPoint">要绑定的终结点</param>
 public static void BindEndPoint(Socket socket, IPEndPoint endPoint)
 {
     if (!socket.IsBound)
     {
         socket.Bind(endPoint);
     }
 }
Example #41
0
        public void Bind(EndPoint localEP)
        {
            _localEndPoint = (IPEndPoint)localEP;

            // Tracing
            UDTTrace("Bind[" + Handle + "]" + localEP.ToString());

#if UDT_FULLTCP
            _tcpSocket.Bind(localEP);
#else
            //---- UDT
            SocketAddress address = ((IPEndPoint)localEP).Serialize();

            byte[] addressBuffer = new byte[address.Size];

            for (int index = 0; index < address.Size; index++)
            {
                addressBuffer[index] = address[index];
            }

            if (UDT_ERROR == API_Bind(_handle, addressBuffer, address.Size))
            {
                throw new UDTSocketException();
            }
#endif
        }
Example #42
0
 public void Start()
 {
     _layerFactory = new OwinHandlerFactory(_parameters.OwinApp, _parameters.OwinCapabilities);
     _ipIsLocalChecker = new IpIsLocalChecker();
     _connectionAllocationStrategy = _parameters.ConnectionAllocationStrategy;
     var isSsl = _parameters.Certificate != null;
     _layerFactory = new Transport2HttpFactory(_parameters.BufferSize, isSsl, _parameters.ServerHeader, _ipIsLocalChecker, _layerFactory);
     if (isSsl)
     {
         _layerFactory = new SslTransportFactory(_parameters, _layerFactory);
     }
     ListenSocket = new Socket(_parameters.EndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
     var start = DateTime.UtcNow;
     while (true)
     {
         try
         {
             ListenSocket.Bind(_parameters.EndPoint);
             break;
         }
         catch when(start + _parameters.RetrySocketBindingTime > DateTime.UtcNow)
         {
         }
         Thread.Sleep(50);
     }
     ListenSocket.Listen(100);
     var initialConnectionCount = _connectionAllocationStrategy.CalculateNewConnectionCount(0, 0);
     AllocatedConnections = initialConnectionCount;
     _blocks.Add(new ConnectionBlock(this, _layerFactory, initialConnectionCount));
 }
Example #43
0
        public void server()
        {
            s.Bind(new IPEndPoint(IPAddress.Any, 12345));
            s.Listen(1);

            serverSocket = s.Accept();
        }
Example #44
0
        public void run()
        {
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, ChatSetting.port);

            Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            newsock.Bind(ipep);
            newsock.Listen(10);

            while (true)
            {
                Socket socket = newsock.Accept();
                Console.WriteLine("�����@�ӷs�s�u!");
                ChatSocket client = new ChatSocket(socket);
                try
                {
                    clientList.Add(client);
                    client.newListener(processMsgComeIn);
                }
                catch
                {
                }
            //                clientList.Remove(client);
            }
            //	  newsock.Close();
        }
Example #45
0
        //private Thread _thThread;
        /// <summary>
        /// 开启TCP服务
        /// </summary>
        protected void StartTCP()
        {
            if (!_tcpEnabled && _running)
            {
                VerifyEndpointAddress(TcpEndPoint);

                _tcpListen = new System.Net.Sockets.Socket(TcpEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

                try
                {
                    _tcpListen.Bind(TcpEndPoint);
                }
                catch (Exception ex)
                {
                    Log.Error(string.Format("Could not bind to Address {0}: {1}", TcpEndPoint, ex));
                    Csl.Wl(string.Format("Could not bind to Address {0}: {1}", TcpEndPoint, ex));
                    return;
                }

                _tcpListen.Listen(CfgMgr.BasicCfg.MaxSimultaneousAcceptOps);
                SocketHelpers.SetListenSocketOptions(_tcpListen);
                _tcpEnabled = true;
                StartAccept(null);

                Log.Info(string.Format("Endpoint {0} start listening", TcpEndPoint));
            }
        }
Example #46
0
        public static void StartServer()
        {
            IPAddress ip = IPAddress.Parse("127.0.0.1");
            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                serverSocket.Bind(new IPEndPoint(ip, myProt));  //绑定IP地址:端口  
                serverSocket.Listen(10);    //设定最多10个排队连接请求   

                Console.WriteLine("启动监听{0}成功\n", serverSocket.LocalEndPoint.ToString());
                while (true)
                {
                    allDone.Reset();
                    serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), serverSocket);
                    allDone.WaitOne();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            //通过Clientsoket发送数据  
            //Thread myThread = new Thread(ListenClientConnect);
            //myThread.Start();
            Console.ReadLine();

        }
Example #47
0
 private void SetUpServer(int countReintentos = 0)
 {
     try
     {
         if (ListenerSocker == null)
         {
             return;
         }
         ListenerSocker.Bind(new IPEndPoint(IPAddress.Any, port));
         ListenerSocker.Listen(0x7FFFFFFF);
         ListenerSocker.BeginAccept(new AsyncCallback(AcceptCallback), null);
     }
     catch (Exception e)
     {
         Log.Log.GetLog().Error(this, "SetUpServer", e);
         Thread.Sleep(5000);
         if (countReintentos > 10)
         {
             Log.Log.GetLog().Info(this, "Fin Reintentos - SetUpServer - " + countReintentos);
             return;
         }
         Log.Log.GetLog().Info(this, "Reintentando - SetUpServer - " + countReintentos);
         SetUpServer(countReintentos + 1);
     }
 }
Example #48
0
        //Main
        static void Main(string[] args)
        {
            ILog log = LogManager.GetLogger(typeof(Program)); //Added
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
            svrSkt = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            svrSkt.Bind(new IPEndPoint(IPAddress.Any, 2050));
            svrSkt.Listen(0xff);
            svrSkt.BeginAccept(Listen, null);
            Console.CancelKeyPress += (sender, e) =>
            {
                Console.WriteLine("Saving Please Wait...");
                svrSkt.Close();
                foreach (var i in RealmManager.Clients.Values.ToArray())
                {
                    i.Save();
                    i.Disconnect();
                }
                Console.WriteLine("\nClosing...");
                Thread.Sleep(100);
                Environment.Exit(0);
            };

            Console.ForegroundColor = ConsoleColor.Green;
            Console.Title = "Server Engine";
            Console.WriteLine("Accepting connections at port " + port + ".");
            HostPolicyServer();
            RealmManager.CoreTickLoop();
        }
Example #49
0
        private void StartListening()
        {
            try
            {
                var listener = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                listener.Bind(_iPEndPoint);
                listener.Listen(200);
                _isStart = true;
                while (_isStart)
                {
                    _acceptEvent.AcceptSocket = null;
                    _allDone.Reset();
                    var pending = listener.AcceptAsync(_acceptEvent);

                    if (!pending)
                    {
                        Accept_Completed(null, _acceptEvent);
                    }
                    _allDone.WaitOne();
                }
            }
            catch (Exception.Exception ex)
            {
                throw ex;
            }
        }
Example #50
0
		/**
		 * Asynchronously connects to the localhost server on the cached port number.
		 * Sets up a TCP socket attempting to contact localhost:outPort, and a 
		 * corresponding UDP server, bound to the inPort.
		 * 
		 * UNDONE: Think about establishing TCP communication to request what port to set up,
		 * in case ports can't be directly forwarded, etc. and Unity doesn't know.
		 * 
		 * Returns True if the connection was successful, false otherwise.
		 */
		public bool connectAsync(){
			try { 
				/* Create TCP socket for authenticated communication */
				endpt = new IPEndPoint(IPAddress.Parse(host), outPort); 
				clientAuth = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

				clientAuth.BeginConnect(endpt, new AsyncCallback(connectCallback), clientAuth);

				/* Set up nondurable UDP server for receiving actions*/
				server = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
				server.Blocking = false;

				/*Set up nondurable UDP client to send gamestate */
				IPEndPoint RemoteEndPoint= new IPEndPoint(IPAddress.Parse(host), outPort);
				clientGameState = new Socket(AddressFamily.InterNetwork,SocketType.Dgram, ProtocolType.Udp);

				/* Bind to UDP host port */
				IPEndPoint inpt = new IPEndPoint(IPAddress.Parse(host), inPort);
				server.Bind (inpt);
				return true;

			} catch (Exception e){
				Debug.Log (e);
				return false;
			}
		}
        /// <summary>
        /// Begin the connection with host.
        /// </summary>
        internal void BeginConnect()
        {
            if (!Disposed)
            {
                //----- Create Socket!
                FSocket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                FSocket.Bind(InternalLocalEndPoint);
                FSocket.ReceiveBufferSize = Host.SocketBufferSize;
                FSocket.SendBufferSize    = Host.SocketBufferSize;

                FReconnectTimer.Change(Timeout.Infinite, Timeout.Infinite);

                SocketAsyncEventArgs e = new SocketAsyncEventArgs();
                e.Completed += new EventHandler <SocketAsyncEventArgs>(BeginConnectCallbackAsync);
                e.UserToken  = this;

                if (FProxyInfo == null)
                {
                    e.RemoteEndPoint = FRemoteEndPoint;
                }
                else
                {
                    FProxyInfo.Completed   = false;
                    FProxyInfo.SOCKS5Phase = SOCKS5Phase.spIdle;

                    e.RemoteEndPoint = FProxyInfo.ProxyEndPoint;
                }

                if (!FSocket.ConnectAsync(e))
                {
                    BeginConnectCallbackAsync(this, e);
                }
            }
        }
Example #52
0
 public ClientThread()
 {
     listenPort = SRLibFun.StringConvertToInt32(SRConfig.Instance.GetAppString("Port"));
     socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     socketWatch.Bind(new IPEndPoint(GetIP(), listenPort));
     socketWatch.Listen(10);
 }
Example #53
0
        public UdpSocket(System.Net.Sockets.Socket socket, int localPort, string ipAddress)
        {
            if (socket == null)
            {
                throw new ArgumentNullException("socket");
            }

            _Socket    = socket;
            _LocalPort = localPort;

            IPAddress localIP = null;

            if (String.IsNullOrEmpty(ipAddress))
            {
                localIP = IPAddress.Any;
            }
            else
            {
                localIP = IPAddress.Parse(ipAddress);
            }

            _Socket.Bind(new IPEndPoint(localIP, localPort));
            if (_LocalPort == 0)
            {
                _LocalPort = (_Socket.LocalEndPoint as IPEndPoint).Port;
            }
        }
Example #54
0
        //static void Main(string[] args, int a)
        public void send()
        {
            String name = Id.name;
            String a1 = "aantal schapen dood";
            String a2 = link.a.ToString();

            Socket sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            sck.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 23));
            sck.Listen(0);

            Socket acc = sck.Accept();

            byte[] buffer = Encoding.Default.GetBytes(name);

            byte[] buffer1 = Encoding.Default.GetBytes(a1 + name);
            acc.Send(buffer, 0, buffer.Length, 0);
            acc.Send(buffer1, 0, buffer.Length, 0);

            buffer = new byte[255];
            int rec = acc.Receive(buffer, 0, buffer.Length, 0);
            Array.Resize(ref buffer, rec);

            Console.WriteLine("Received: {0}", Encoding.Default.GetString(buffer));

            sck.Close();
            acc.Close();

            Console.Read();
        }
Example #55
0
        /// <summary>
        /// Start listening and close the current socket connection.
        /// </summary>
        /// <remarks>This method blocks the current thread.</remarks>
        public virtual void StartListening()
        {
            try
            {
                // Clear last error.
                ClearLastError();

                // If not listening then attempt to start the server.
                if (!_isListening)
                {
                    // Create the end point from the address and port.
                    IPEndPoint endPoint = new IPEndPoint(_address, _port);

                    // Create the server binding and start listening.
                    _socket = new Socket(endPoint.AddressFamily, _socketType, _protocolType);
                    _socket.Bind(endPoint);

                    // Trigger the start listening event.
                    StartListeningEvent();

                    // Post accepts on the listening socket.
                    StartAccept();
                }
            }
            catch (Exception ex)
            {
                // Stop listening.
                StopListening();

                SetLastError(ex);

                // Trigger the stop listening event.
                StopListeningEvent(ex);
            }
        }
Example #56
0
    /// <summary>
    /// Запуск сервера
    /// </summary>
    public void Start()
    {
        try
        {
            if (_isListen)
            {
                Log.Logger.Information("Сокет сервер уже запущен");
                return;
            }

            if (_serverEndPoint == null)
            {
                Log.Logger.Information("Не создан экземпляр сервера");
                return;
            }

            _serverSocket.Bind(_serverEndPoint);
            _serverSocket.Listen(100);

            _isListen = true;

            Log.Logger.Information("Ожидание новых подключений...");

            _acceptConnectionsTokenSource = new CancellationTokenSource();
            _acceptConnectionsToken       = _acceptConnectionsTokenSource.Token;

            _acceptConnections = Task.Run(AcceptConnectionsAsync, _acceptConnectionsToken);
        }
        catch (Exception ex)
        {
            Log.Logger.Information($"Произошла ошибка при включении сервера: {ex}");
        }
    }
Example #57
0
            private static System.Net.Sockets.Socket ConnectSocket(string server, int port)
            {
                port = 8412;
                System.Net.Sockets.Socket s = null;
                IPHostEntry hostEntry       = null;

                // Get host related information.
                hostEntry = Dns.GetHostEntry(server);

                // Loop through the AddressList to obtain the supported AddressFamily. This is to avoid
                // an exception that occurs when the host IP Address is not compatible with the address family
                // (typical in the IPv6 case).
                foreach (IPAddress address in hostEntry.AddressList)
                {
                    IPEndPoint ipe = new IPEndPoint(address, port);
                    System.Net.Sockets.Socket tempSocket =
                        new System.Net.Sockets.Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                    tempSocket.Bind(ipe);
                    tempSocket.Connect(ipe);

                    if (tempSocket.Connected)
                    {
                        s = tempSocket;
                        break;
                    }
                    else
                    {
                        continue;
                    }
                }
                return(s);
            }
Example #58
0
		private void InitializeNetwork()
		{
			lock (m_initializeLock)
			{
				m_configuration.Lock();

				if (m_status == NetPeerStatus.Running)
					return;

				InitializePools();

				m_releasedIncomingMessages.Clear();
				m_unsentUnconnectedMessages.Clear();
				m_handshakes.Clear();

				// bind to socket
				IPEndPoint iep = null;

				iep = new IPEndPoint(m_configuration.LocalAddress, m_configuration.Port);
				EndPoint ep = (EndPoint)iep;

				m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
				m_socket.ReceiveBufferSize = m_configuration.ReceiveBufferSize;
				m_socket.SendBufferSize = m_configuration.SendBufferSize;
				m_socket.Blocking = false;
				m_socket.Bind(ep);

				IPEndPoint boundEp = m_socket.LocalEndPoint as IPEndPoint;
				LogDebug("Socket bound to " + boundEp + ": " + m_socket.IsBound);
				m_listenPort = boundEp.Port;

				m_receiveBuffer = new byte[m_configuration.ReceiveBufferSize];
				m_sendBuffer = new byte[m_configuration.SendBufferSize];
				m_readHelperMessage = new NetIncomingMessage(NetIncomingMessageType.Error);
				m_readHelperMessage.m_data = m_receiveBuffer;

				byte[] macBytes = new byte[8];
				NetRandom.Instance.NextBytes(macBytes);

#if IS_MAC_AVAILABLE
			System.Net.NetworkInformation.PhysicalAddress pa = NetUtility.GetMacAddress();
			if (pa != null)
			{
				macBytes = pa.GetAddressBytes();
				LogVerbose("Mac address is " + NetUtility.ToHexString(macBytes));
			}
			else
			{
				LogWarning("Failed to get Mac address");
			}
#endif
				byte[] epBytes = BitConverter.GetBytes(boundEp.GetHashCode());
				byte[] combined = new byte[epBytes.Length + macBytes.Length];
				Array.Copy(epBytes, 0, combined, 0, epBytes.Length);
				Array.Copy(macBytes, 0, combined, epBytes.Length, macBytes.Length);
				m_uniqueIdentifier = BitConverter.ToInt64(SHA1.Create().ComputeHash(combined), 0);

				m_status = NetPeerStatus.Running;
			}
		}
Example #59
0
        private void Listen()
        {
            // 包含了一个IP地址
            var ip = IPAddress.Parse("127.0.0.1");

            // 包含了一对IP地址和端口号
            var iep = new IPEndPoint(ip, 8500);

            /*
             * 创建一个Socket;
             *
             * 1.AddressFamily.InterNetWork:使用 IP4地址。
             *
             * 2.SocketType.Stream:支持可靠、双向、基于连接的字节流,
             * 而不重复数据。此类型的 Socket 与单个对方主机进行通信,
             * 并且在通信开始之前需要远程主机连接。
             * Stream 使用传输控制协议 (Tcp) ProtocolType 和 InterNetworkAddressFamily。
             *
             * 3.ProtocolType.Tcp:使用传输控制协议。
             */
            var socket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // 绑定一个本地的IP和端口号(IPEndPoint),socket监听哪个端口
            socket.Bind(iep);

            // 定义byte数组存放从客户端接收过来的数据
            var buffer = new byte[1024 * 1024];

            // 同一个时间点过来10个客户端,排队
            socket.Listen(10);

            lblMsg.Text = string.Format("开始在{0}{1}上监听", iep.Address.ToString(), iep.Port.ToString());

            System.Net.Sockets.Socket client;
            int recv;

            while (true)
            {
                // 接收连接并返回一个新的Socket
                client = socket.Accept();

                // 将接收过来的数据放到buffer中,并返回实际接受数据的长度
                recv = client.Receive(buffer);

                // 将字节转换成字符串
                var cliMsg = Encoding.UTF8.GetString(buffer, 0, recv);

                cliMsg = DateTime.Now.ToShortTimeString() + "," + client.RemoteEndPoint + "发来信息:" + cliMsg;

                this.listBox1.Items.Add(cliMsg);

                var serMsg  = "服务器返回信息:OK.";
                var serByte = Encoding.UTF8.GetBytes(serMsg);

                // 输出数据到Socket
                client.Send(serByte);
            }
        }
Example #60
0
        static void Main(string[] args)
        {
            socket.Bind(new IPEndPoint(IPAddress.Any, 100));
            socket.Listen(50);
            Socket client = socket.Accept();

            byte[] buffer = new byte[1024];
            client.Receive(buffer);
        }