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


C# Socket.Bind方法代码示例

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


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

示例1: Wrong2

 public static void Wrong2()
 {
     var socket = new Socket();
     socket.Bind(new EndPoint());
     socket.Listen(1000);
     socket.Bind(new EndPoint());
     // Called Bind more than once.
 }
开发者ID:michaellperry,项目名称:Provable-APIs,代码行数:8,代码来源:3-Constructors.cs

示例2: StartListening

    public static void StartListening()
    {
        IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
        IPAddress ipAddress = ipHostInfo.AddressList[0];
        IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);

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

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

            while (true)
            {
                AllDone.Reset();
                listener.BeginAccept(AcceptCallback, listener);
                AllDone.WaitOne();
            }
        }
        catch (Exception e)
        {
            throw;
        }
    }
开发者ID:EttienneS,项目名称:Contingency,代码行数:25,代码来源:Program.cs

示例3: Sync_init

    public static void Sync_init()
    {
        sync_srv_state = true;
        Syncsck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        Syncsck.Bind(new IPEndPoint(IPAddress.Parse(RmIp), SyncPort));
        Syncsck.Listen(5);
        Syncsck.ReceiveTimeout = 12000;
        while (true)
        {
            try
            {
                Cmdsck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                Cmdsck.Connect(new IPEndPoint(IPAddress.Parse(RmIp), CmdPort));
                sync_srv_state = true;
            }
            catch
            {
                sync_srv_state = false;
                Console.WriteLine("Con. False");
                Thread.Sleep(5000);
            }
            if (sync_srv_state == true)
            {
                Thread Syncproc = new Thread(Sync_srv);
                Syncproc.Start();
                Thread.Sleep(5000);
                while (sync_srv_state == true) { Thread.Sleep(1000); }
                Cmdsck.Close();
            }
        }

    }
开发者ID:frengc0641,项目名称:ConsoleT,代码行数:32,代码来源:Sync.cs

示例4: Main

        static void Main(string[] args)
        {
            using (var context = NetMQContext.Create())
            using (var udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            using (var poller = new Poller())
            {
                // Ask OS to let us do broadcasts from socket
                udpSocket.SetSocketOption(SocketOptionLevel.Udp, SocketOptionName.Broadcast, 1);

                // Bind UDP socket to local port so we can receive pings
                udpSocket.Bind(new IPEndPoint(IPAddress.Any, PingPortNumber));

                // We use zmq_poll to wait for activity on the UDP socket, because
                // this function works on non-0MQ file handles. We send a beacon
                // once a second, and we collect and report beacons that come in
                // from other nodes:

                poller.AddPollInSocket(udpSocket, socket => { });
                poller.PollTillCancelledNonBlocking();
                //poller.ad
                //var poller = new z
                //var pollItemsList = new List<ZPollItem>();
                //pollItemsList.Add(new ZPollItem(ZPoll.In));
                //var pollItem = ZPollItem.CreateReceiver();
                //ZMessage message;
                //ZError error;
                //pollItem.ReceiveMessage(udpSocket, out message, out error);
                //pollItem.ReceiveMessage = (ZSocket socket, out ZMessage message, out ZError error) =>

                // Send first ping right away

            }
        }
开发者ID:dshaneg,项目名称:zmqpoc,代码行数:33,代码来源:Program.cs

示例5: Main

	static void Main (string [] args)
	{
		byte [] buffer = new byte [10];

		IPAddress ipAddress = IPAddress.Loopback;
		IPEndPoint localEndPoint = new IPEndPoint (ipAddress, 12521);

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

		listener.Bind (localEndPoint);
		listener.Listen (5);

		Socket handler = listener.Accept ();

		int bytesRec = handler.Receive (buffer, 0, 10, SocketFlags.None);

		string msg = Encoding.ASCII.GetString (buffer, 0, bytesRec);
		if (msg != "hello") {
			string dir = AppDomain.CurrentDomain.BaseDirectory;
			using (StreamWriter sw = File.CreateText (Path.Combine (dir, "error"))) {
				sw.WriteLine (msg);
			}
		}

		handler.Close ();

		Thread.Sleep (200);
	}
开发者ID:mono,项目名称:gert,代码行数:29,代码来源:server.cs

示例6: StartListening

 public void StartListening(int port) 
 { 
     try { // Resolve local name to get IP address 
         IPHostEntry entry = Dns.Resolve(Dns.GetHostName()); 
         IPAddress ip = entry.AddressList[0]; 
         // Create an end-point for local IP and port 
         IPEndPoint ep = new IPEndPoint(ip, port); 
         if(isLogging)
             TraceLog.myWriter.WriteLine ("Address: " + ep.Address.ToString() +" : " + ep.Port.ToString(),"StartListening"); 
         EventLog.WriteEntry("MMFCache Async Listener","Listener started on IP: " + 
                 ip.ToString() + " and Port: " +port.ToString()+ "."); 
         // Create our socket for listening 
         s = new Socket(ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp); 
         // Bind and listen with a queue of 100 
         s.Bind(ep); 
         s.Listen(100); 
         // Setup our delegates for performing callbacks 
         acceptCallback = new AsyncCallback(AcceptCallback); 
         receiveCallback = new AsyncCallback(ReceiveCallback); 
         sendCallback = new AsyncCallback(SendCallback); 
         // Set the "Accept" process in motion 
         s.BeginAccept(acceptCallback, s); 
     } 
     catch(SocketException e) { 
         Console.Write("SocketException: "+ e.Message); 
     } 
 } 
开发者ID:ppatoria,项目名称:SoftwareDevelopment,代码行数:27,代码来源:Program.cs

示例7: Initialize

        public void Initialize(IDatabaseHandler dbHandler)
        {
            GlobalContext = new Context(1);
            ValkWFStepPoller.PollContext = GlobalContext;
            ValkWFActivator.ActContext = GlobalContext;
            ValkQueueWFSteps.QueueContext = GlobalContext;
            //setup our inprocess communication
            ActivatorControlIntraComm = GlobalContext.Socket(SocketType.REQ);
            ActivatorControlIntraComm.Bind("inproc://activatorcontrol");
            //poller requires activator, goes after
            PollerControlIntraComm = GlobalContext.Socket(SocketType.REQ);
            PollerControlIntraComm.Bind("inproc://pollercontrol");

            QueueControlIntraComm = GlobalContext.Socket(SocketType.REQ);
            QueueControlIntraComm.Bind("inproc://queuecontrol");

            //anonymous function to pass in dbhandler without parameterizedthreadstart obscurities
            WFStepQueue = new Thread(() => ValkQueueWFSteps.RunQueue(dbHandler));
            WFStepQueue.Start();

            Activator = new Thread(() => ValkWFActivator.ActivateResponder(dbHandler));
            Activator.Start();

            Poller = new Thread(() => ValkWFStepPoller.StartPolling(dbHandler));
            Poller.Start();
        }
开发者ID:jmlothian,项目名称:ValkyrieWF,代码行数:26,代码来源:ValkController.cs

示例8: ServerSocket

    public ServerSocket()
    {
        data = new byte[102400];

        //得到本机IP,设置TCP端口号
        ipep = new IPEndPoint(IPAddress.Any, 6000);
        newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

        //绑定网络地址
        newsock.Bind(ipep);

        //得到客户机IP
        sender = new IPEndPoint(IPAddress.Any, 0);
        Remote = (EndPoint)(sender);

        ////客户机连接成功后,发送欢迎信息
        //string welcome = "Welcome ! ";

        ////字符串与字节数组相互转换
        //data = Encoding.ASCII.GetBytes(welcome);

        ////发送信息
        //newsock.SendTo(data, data.Length, SocketFlags.None, Remote);

        texture = new Texture2D(960, 720);

        thread = new Thread(start);
        thread.IsBackground = true;
        thread.Start();
        Debug.Log("Thread start");
    }
开发者ID:gjwGithub,项目名称:Cardboard,代码行数:31,代码来源:ServerSocket.cs

示例9: Main

	static void Main (string [] args)
	{
		int port;

		Random random = new Random ();
		Socket socket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

		do {
			port = random.Next (0xc350, 0xffdc);
			IPEndPoint localEP = new IPEndPoint (IPAddress.Loopback, port);
			try {
				socket.Bind (localEP);
				break;
			} catch {
			}
		} while (true);

		socket.Close ();

		IPEndPoint LocalEP = new IPEndPoint (IPAddress.Loopback, port);
		Socket ListeningSocket = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
		ListeningSocket.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
		ListeningSocket.Bind (LocalEP);
		ListeningSocket.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.AddMembership,
			new MulticastOption (IPAddress.Parse ("239.255.255.250"), IPAddress.Loopback));
		ListeningSocket.Close ();
	}
开发者ID:mono,项目名称:gert,代码行数:27,代码来源:test.cs

示例10: Start

	 public void Start ()
	{
		if(clientSocket!=null && clientSocket.Connected)return ;

		//服务器端口
		IPEndPoint ipEndpoint = new IPEndPoint (IPAddress.Any,point);
		//创建Socket对象
		clientSocket = new Socket (AddressFamily.InterNetwork,socketType,protocolType);

		//这是一个异步的建立连接,当连接建立成功时调用connectCallback方法
		//IAsyncResult result = clientSocket.BeginConnect (ipEndpoint,new AsyncCallback (connectCallback),clientSocket);
		
		//这里做一个超时的监测,当连接超过5秒还没成功表示超时
		//bool success = result.AsyncWaitHandle.WaitOne( 5000, true );

		//绑定网络地址
		clientSocket.Bind(ipEndpoint);
		Debug.Log("This is a Server, host name is {"+Dns.GetHostName()+"}");

			//与socket建立连接成功,开启线程接受服务端数据。
			//worldpackage = new List<JFPackage.WorldPackage>();
			thread = new Thread(new ThreadStart(ReceiveSorket));
			thread.IsBackground = true;
			thread.Start();

	}
开发者ID:TowerSay,项目名称:Tower,代码行数:26,代码来源:P2PServer.cs

示例11: Start

 // Use this for initialization
 void Start()
 {
     // Set up Server End Point for sending packets.
     IPHostEntry serverHostEntry = Dns.GetHostEntry(serverIp);
     IPAddress serverIpAddress = serverHostEntry.AddressList[0];
     serverEndPoint = new IPEndPoint(serverIpAddress, serverPort);
     Debug.Log("Server IPEndPoint: " + serverEndPoint.ToString());
     // Set up Client End Point for receiving packets.
     IPHostEntry clientHostEntry = Dns.GetHostEntry(Dns.GetHostName());
     IPAddress clientIpAddress = IPAddress.Any;
     foreach (IPAddress ip in clientHostEntry.AddressList) {
         if (ip.AddressFamily == AddressFamily.InterNetwork) {
             clientIpAddress = ip;
         }
     }
     clientEndPoint = new IPEndPoint(clientIpAddress, serverPort);
     Debug.Log("Client IPEndPoint: " + clientEndPoint.ToString());
     // Create socket for client and bind to Client End Point (Ip/Port).
     clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
     try {
         clientSocket.Bind(clientEndPoint);
     }
     catch (Exception e) {
         Debug.Log("Winsock error: " + e.ToString());
     }
 }
开发者ID:Victory-Game-Studios,项目名称:Oldentide,代码行数:27,代码来源:NetworkInterface.cs

示例12: Success

        public void Success()
        {
            ManualResetEvent completed = new ManualResetEvent(false);

            if (Socket.OSSupportsIPv4)
            {
                using (Socket receiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
                {
                    int port = receiver.BindToAnonymousPort(IPAddress.Loopback);
                    receiver.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.PacketInformation, true);

                    Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                    sender.Bind(new IPEndPoint(IPAddress.Loopback, 0));
                    sender.SendTo(new byte[1024], new IPEndPoint(IPAddress.Loopback, port));

                    SocketAsyncEventArgs args = new SocketAsyncEventArgs();
                    args.RemoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
                    args.SetBuffer(new byte[1024], 0, 1024);
                    args.Completed += OnCompleted;
                    args.UserToken = completed;

                    Assert.True(receiver.ReceiveMessageFromAsync(args));

                    Assert.True(completed.WaitOne(Configuration.PassingTestTimeout), "Timeout while waiting for connection");

                    Assert.Equal(1024, args.BytesTransferred);
                    Assert.Equal(sender.LocalEndPoint, args.RemoteEndPoint);
                    Assert.Equal(((IPEndPoint)sender.LocalEndPoint).Address, args.ReceiveMessageFromPacketInfo.Address);

                    sender.Dispose();
                }
            }
        }
开发者ID:rainersigwald,项目名称:corefx,代码行数:33,代码来源:ReceiveMessageFromAsync.cs

示例13: MessagePublisher

 public MessagePublisher(OnTheWireBusConfiguration configuration)
 {
     _configuration = configuration;
     _context = new Context(configuration.MaxThreads);
     _publisher = _context.Socket(SocketType.PUB);
     _publisher.Bind(configuration.FullyQualifiedAddress);
 }
开发者ID:brandongrossutti,项目名称:EventStore,代码行数:7,代码来源:MessagePublisher.cs

示例14: UDPServer

	public UDPServer()
	{
		try
		{
			// Iniciando array de clientes conectados
			this.listaClientes = new ArrayList();
			entrantPackagesCounter = 0;
			sendingPackagesCounter = 0;			
			// Inicializando el delegado para actualizar estado
			//this.updateStatusDelegate = new UpdateStatusDelegate(this.UpdateStatus);
		
			// Inicializando el socket
			serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
			
			// Inicializar IP y escuhar puerto 30000
			IPEndPoint server = new IPEndPoint(IPAddress.Any, 30001);
			
			// Asociar socket con el IP dado y el puerto
			serverSocket.Bind(server);
			
			// Inicializar IPEndpoint de los clientes
			IPEndPoint clients = new IPEndPoint(IPAddress.Any, 0);
			
			// Inicializar Endpoint de clientes
			EndPoint epSender = (EndPoint)clients;
			
			// Empezar a escuhar datos entrantes
			serverSocket.BeginReceiveFrom(this.dataStream, 0, this.dataStream.Length, SocketFlags.None, ref epSender, new AsyncCallback(ReceiveData), epSender);

		}
		catch (Exception ex)
		{
			//Debug.Log("Error al cargar servidor: " + ex.Message+ " ---UDP ");
		}
	}
开发者ID:PJEstrada,项目名称:proyecto1-redes,代码行数:35,代码来源:UDPServer.cs

示例15: TZmqServer

		public TZmqServer (TProcessor processor, Context ctx, String endpoint, SocketType sockType)
		{
			new TSimpleServer (processor,null);
			_socket = ctx.Socket (sockType);
			_socket.Bind (endpoint);
			_processor = processor;
		}
开发者ID:ConfusedReality,项目名称:pkg_serialization_thrift,代码行数:7,代码来源:TZmqServer.cs


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