当前位置: 首页>>代码示例>>C#>>正文


C# Socket.Bind方法代码示例

本文整理汇总了C#中System.Net.Sockets.Socket.Bind方法的典型用法代码示例。如果您正苦于以下问题:C# Socket.Bind方法的具体用法?C# Socket.Bind怎么用?C# Socket.Bind使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Net.Sockets.Socket的用法示例。


在下文中一共展示了Socket.Bind方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: WebServer

        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();
        }
开发者ID:colethecoder,项目名称:NetduinoTrafficLights,代码行数:28,代码来源:WebServer.cs

示例2: Server

        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 { }
            }
        }
开发者ID:jiashida,项目名称:super-trojan-horse,代码行数:34,代码来源:BroadcastScan.cs

示例3: server_socket

        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 ) );
             }
        }
开发者ID:mbrock,项目名称:bigloo-llvm,代码行数:29,代码来源:server_socket.cs

示例4: RecieveCallback

 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);
         }
     }
 }
开发者ID:MohammedAbuissa,项目名称:Client_Server,代码行数:35,代码来源:UDPServer.cs

示例5: Http2SocketServer

        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();
        }
开发者ID:Tratcher,项目名称:HTTP-SPEED-PLUS-MOBILITY,代码行数:25,代码来源:Http2SocketServer.cs

示例6: DccListener

 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();
 }
开发者ID:jaddie,项目名称:DarkWaterSupportBot,代码行数:28,代码来源:DccListener.cs

示例7: StartListening

        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;
        }
开发者ID:kamilion,项目名称:WISP,代码行数:49,代码来源:UDPListenerSimplex.cs

示例8: OpenChannel

        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();
            }
        }
开发者ID:yonglehou,项目名称:cli-1,代码行数:26,代码来源:Program.cs

示例9: connectAsync

		/**
		 * 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;
			}
		}
开发者ID:rhyschris,项目名称:CS194Project,代码行数:36,代码来源:AsyncAIClient.cs

示例10: CreateTcp

 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 );
 }
开发者ID:yfakariya,项目名称:msgpack-rpc,代码行数:7,代码来源:ServerMock.cs

示例11: ManagmentService

        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);
        }
开发者ID:amoein,项目名称:AsyncClient,代码行数:27,代码来源:ManagmentService.cs

示例12: Main

        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();
        }
开发者ID:vin120,项目名称:c-shap-code,代码行数:31,代码来源:Program.cs

示例13: Server

        /// <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);
        }
开发者ID:h07r0d,项目名称:Netduino-Aquarium-Controller,代码行数:30,代码来源:Server.cs

示例14: send

        //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();
        }
开发者ID:rickoskam,项目名称:ShepherdGame,代码行数:31,代码来源:test1.cs

示例15: Start

        /// <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;
            }
        }
开发者ID:kinghuc,项目名称:521266750_qq_com,代码行数:34,代码来源:TcpAsyncSocketListener.cs


注:本文中的System.Net.Sockets.Socket.Bind方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。