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


C# Socket.Listen方法代码示例

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


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

示例1: StartListening

	public static void StartListening()
	{
		// Data buffer for incoming data.     
		// Establish the local endpoint for the socket.     
		// The DNS name of the computer     
		// running the listener is "host.contoso.com".     
		//IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
		//IPAddress ipAddress = ipHostInfo.AddressList[0];
		IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
		IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
		// Create a TCP/IP socket.     
		Socket listener = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
		// Bind the socket to the local     
		//endpoint and listen for incoming connections.     
		try
		{
			listener.Bind(localEndPoint);
			listener.Listen(100);
			while (!stop)
			{
				// Set the event to nonsignaled state.     
				allDone.Reset();
				// Start an asynchronous socket to listen for connections.     
				LogMgr.Log("Waiting for a connection...");
				listener.BeginAccept(new AsyncCallback(AcceptCallback),listener);
				// Wait until a connection is made before continuing.     
				allDone.WaitOne();
			}
		}
		catch (Exception e)
		{
			LogMgr.LogError(e);
		}

	}
开发者ID:learnUnity,项目名称:KU_NET,代码行数:35,代码来源:AsynchronousSocketListener.cs

示例2: 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

示例3: Server

	Server ()
	{
		_listener = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
		_listener.Bind (new IPEndPoint (IPAddress.Loopback, 10000));
		_listener.Listen (10);
		_listener.BeginAccept (new AsyncCallback (OnAccept), _listener);
	}
开发者ID:mono,项目名称:gert,代码行数:7,代码来源:server.cs

示例4: CreateTcpServer

    public bool CreateTcpServer(string ip, int listenPort)
    {
        _port = listenPort;
        _listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        foreach (IPAddress address in Dns.GetHostEntry(ip).AddressList)
        {
            try
            {
                IPAddress hostIP = address;
                IPEndPoint ipe = new IPEndPoint(address, _port);

                _listener.Bind(ipe);
                _listener.Listen(_maxConnections);
                _listener.BeginAccept(new System.AsyncCallback(ListenTcpClient), _listener);

                break;

            }
            catch (System.Exception)
            {
                return false;
            }
        }

        return true;
    }
开发者ID:5941120,项目名称:UnitySample,代码行数:27,代码来源:NetTCPServer.cs

示例5: send

    //static void Main(string[] args, int a)
    public static void send()
    {
        String name = Id.name;
            String a2 = link.a.ToString();
            int y = 9;
            String a3 = y.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();
        // all the data will  be sent in one buffer.
            byte[] buffer = Encoding.Default.GetBytes(name + a2 + a3);

            acc.Send(buffer, 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,代码行数:28,代码来源:PostData.cs

示例6: Main

    // main.. how we start it all up
    static int Main(string[] args)
    {
        // args checker
        if (args.Length != 4)
        {
            System.Console.WriteLine("port_redir.exe <listenIP> <listenPort> <connectIP> <connectPort>");
            return 1;
        }
        // Our socket bind "function" we could just as easily replace this with
        // A Connect_Call and make it a true gender-bender
        IPEndPoint tmpsrv = new IPEndPoint(IPAddress.Parse(args[0]), Int32.Parse(args[1]));
        Socket ipsrv = new Socket(tmpsrv.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
        ipsrv.Bind(tmpsrv);
        ipsrv.Listen(10);

        // loop it so we can continue to accept
        while (true)
        {
            try
            {
                // block till something connects to us
                Socket srv = ipsrv.Accept();
                // Once it does connect to the outbound ip:port
                Socket con = Connect_Call(args[2], Int32.Parse(args[3]));
                // Read and write back and forth to our sockets.
                Thread SrvToCon = new Thread(() => Sock_Relay(srv, con));
                SrvToCon.Start();
                Thread ConToSrv = new Thread(() => Sock_Relay(con, srv));
                ConToSrv.Start();
            }
            catch (Exception e) { Console.WriteLine("{0}", e); }
        }
    }
开发者ID:trump0dump,项目名称:helpful,代码行数:34,代码来源:port_redir.cs

示例7: Awake

	void Awake ()
	{                
        /*
#if UNITY_STANDALONE_WIN || UNITY_EDITOR_WIN
        objPath = "file://" + Application.streamingAssetsPath + "/model2.obj";
#else
#if UNITY_ANDROID
        FileInfo fi = new FileInfo("/sdcard/model.obj");
        if (fi.Exists)
            objPath = "file://" +"/sdcard/model.obj";
        else
            objPath = Application.streamingAssetsPath + "/model2.obj";            
#endif
#endif
         */
#if STANDALONE_DEBUG
        IPAddress ip = IPAddress.Parse("127.0.0.1");
        serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        serverSocket.Bind(new IPEndPoint(ip, myPort));
        serverSocket.Listen(5);
        clientSocket = new List<Socket>();
#endif
        load_state = LoadState.IDLE;
        move_para = new MovePara();
        show_envelop = false;
        show_joint = false;
        show_body = true;

        gameObject.AddComponent<Animation>();
        animation.AddClip(move_para.create_move(Movement.RUN), "run");
        animation.AddClip(move_para.create_move(Movement.JUMP), "jump");
        animation.AddClip(move_para.create_move(Movement.SLIDE), "slide");
	}
开发者ID:chenyufjfz,项目名称:Paoku,代码行数:33,代码来源:OBJ.cs

示例8: ReceiveTimesOut_Throws

        public void ReceiveTimesOut_Throws()
        {
            using (Socket localSocket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
            {
                using (Socket remoteSocket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
                {
                    int port = localSocket.BindToAnonymousPort(IPAddress.IPv6Loopback);
                    localSocket.Listen(1);
                    IAsyncResult localAsync = localSocket.BeginAccept(null, null);

                    remoteSocket.Connect(IPAddress.IPv6Loopback, port);

                    Socket acceptedSocket = localSocket.EndAccept(localAsync);
                    acceptedSocket.ReceiveTimeout = 100;

                    SocketException sockEx = Assert.Throws<SocketException>(() =>
                   {
                       acceptedSocket.Receive(new byte[1]);
                   });

                    Assert.Equal(SocketError.TimedOut, sockEx.SocketErrorCode);
                    Assert.True(acceptedSocket.Connected);
                }
            }
        }
开发者ID:fuwei199006,项目名称:corefx,代码行数:25,代码来源:TimeoutTest.cs

示例9: 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

示例10: 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

示例11: Main

	public static void Main(String []argv)
	{
		IPAddress ip = IPAddress.Loopback;
		Int32 port=1800;
		if(argv.Length>0)
			port = Int32.Parse(argv[0]);	
		IPEndPoint ep = new IPEndPoint(ip,port);
		Socket ss = new Socket(AddressFamily.InterNetwork , 
			SocketType.Stream , ProtocolType.Tcp);
		try
		{
			ss.Bind(ep);
		}
		catch(SocketException err)
		{
			Console.WriteLine("** Error : socket already in use :"+err);
			Console.WriteLine("           Please wait a few secs & try");	
		}
		ss.Listen(-1);
		Console.WriteLine("Server started and running on port {0}.....",port);
		Console.WriteLine("Access URL http://localhost:{0}",port);
		Socket client = null;
		while(true)
		{
			client=ss.Accept();
			SocketMessenger sm=new SocketMessenger(client);
			sm.Start();
		}
		Console.WriteLine(client.LocalEndPoint.ToString()+" CONNECTED ");
		ss.Close();
	}
开发者ID:jjenki11,项目名称:blaze-chem-rendering,代码行数:31,代码来源:httpsrv.cs

示例12: 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

示例13: Start

    /// <summary>
    /// Socket Initialization Place Any Other Code Before the Socket Initialization
    /// </summary>
    private void Start()
    {
        limits.x = -4;
        limits.y =  8;
        limits.z =  4;

        AudioManager.Instance.PlaySound(EAudioPlayType.BGM, audioClip);

        if (toPototatoeFountainOrNotToPotatoeFountain)
        { StartCoroutine(POTATOFOUNTAIN()); } 

        if (socketBehaviour == ESocketBehaviour.Server)
        {
            clients = new List<Socket>();

            buffer = new byte[1024];

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

            IPEndPoint parsedIP = new IPEndPoint(IPAddress.Parse(IP), port);

            mySocket.Bind(parsedIP);
            mySocket.Listen(100);
            mySocket.BeginAccept( new AsyncCallback(AcceptCallback), null );

            return;
        }

        if (socketBehaviour == ESocketBehaviour.Client)
        {
            buffer = new byte[1];
        }
    }
开发者ID:BenDy557,项目名称:Potato,代码行数:36,代码来源:SocketComm.cs

示例14: StartListening

    public static void StartListening()
    {
        // Data buffer for incoming data.
        byte[] bytes = new Byte[1024];

        // Establish the local endpoint for the socket.
        // Dns.GetHostName returns the name of the 
        // host running the application.
        IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
        IPAddress ipAddress = ipHostInfo.AddressList[0];
        IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);

        // Create a TCP/IP socket.
        Socket listener = new Socket(AddressFamily.InterNetwork,
            SocketType.Stream, ProtocolType.Tcp);

        // Bind the socket to the local endpoint and 
        // listen for incoming connections.
        try
        {
            listener.Bind(localEndPoint);
            listener.Listen(10);

            // Start listening for connections.
            while (true)
            {
                Console.WriteLine("Waiting for a connection...");
                // Program is suspended while waiting for an incoming connection.
                Socket handler = listener.Accept();
                data = null;

                // Show the data on the console.
                Console.WriteLine("Text received : {0}", data);
                byte[] msg = null;
                // Echo the data back to the client.
                while (true)
                {
                    data = Guid.NewGuid().ToString();
                    msg = Encoding.ASCII.GetBytes(data);
                    handler.Send(msg);
                    Console.WriteLine("Text sent : {0} {1}", data, DateTime.Now.ToString());
                    
                    System.Threading.Thread.Sleep(1000);
                }

                handler.Shutdown(SocketShutdown.Both);
                handler.Close();
            }

        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }

        Console.WriteLine("\nPress ENTER to continue...");
        Console.ReadLine();

    }
开发者ID:erolirfan,项目名称:SocketToWebSocketProxy,代码行数:59,代码来源:Program.cs

示例15: initServer

    // Use this for initialization
    public void initServer()
    {
        host = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        host.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8889));
        host.Listen(100);

        //host.Close();
    }
开发者ID:pachydermx,项目名称:AirHockeyDemo,代码行数:9,代码来源:SocketTest.cs


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