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


C# Socket.Accept方法代码示例

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


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

示例1: ThresholdExceeded_ThrowsException

        public async Task ThresholdExceeded_ThrowsException(string responseHeaders, int maxResponseHeadersLength, bool shouldSucceed)
        {
            using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                s.Bind(new IPEndPoint(IPAddress.Loopback, 0));
                s.Listen(1);
                var ep = (IPEndPoint)s.LocalEndPoint;

                using (var handler = new HttpClientHandler() { MaxResponseHeadersLength = maxResponseHeadersLength })
                using (var client = new HttpClient(handler))
                {
                    Task<HttpResponseMessage> getAsync = client.GetAsync($"http://{ep.Address}:{ep.Port}", HttpCompletionOption.ResponseHeadersRead);

                    using (Socket server = s.Accept())
                    using (Stream serverStream = new NetworkStream(server, ownsSocket: false))
                    using (StreamReader reader = new StreamReader(serverStream, Encoding.ASCII))
                    {
                        string line;
                        while ((line = reader.ReadLine()) != null && !string.IsNullOrEmpty(line)) ;

                        byte[] headerData = Encoding.ASCII.GetBytes(responseHeaders);
                        serverStream.Write(headerData, 0, headerData.Length);
                    }

                    if (shouldSucceed)
                    {
                        (await getAsync).Dispose();
                    }
                    else
                    {
                        await Assert.ThrowsAsync<HttpRequestException>(() => getAsync);
                    }
                }
            }
        }
开发者ID:SGuyGe,项目名称:corefx,代码行数:35,代码来源:HttpClientHandlerTest.MaxResponseHeadersLength.cs

示例2: Main

        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);

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

示例3: Main

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

示例4: Start

        public void Start()
        {
            IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
            Console.WriteLine("IP=" + ipAddress.ToString());
            Socket CurrentClient = null;
            Socket ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                //On lie la socket au point de communication
                ServerSocket.Bind(new IPEndPoint(ipAddress, ProtocoleImplementation.PORT_ID));
                //On la positionne en mode "écoute"
                ServerSocket.Listen(10);

                while (true)
                {
                    Console.WriteLine("Attente d'une nouvelle connexion...");
                    //L'exécution du thread courant est bloquée jusqu'à ce qu'un nouveau client se connecte
                    CurrentClient = ServerSocket.Accept();
                    Console.WriteLine("Nouveau client:" + CurrentClient.GetHashCode());
                    acceptList.Add(CurrentClient);
                    SocketServer n = new SocketServer(CurrentClient);
                    Thread getReadClients = new Thread(new ThreadStart(n.GetQuery));
                    getReadClients.Start();
                }
            }
            catch (SocketException E)
            {
                Console.WriteLine(E.Message);
            }
        }
开发者ID:Commortel,项目名称:TpBruteWithArch,代码行数:31,代码来源:Serveur.cs

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

示例6: Main

 public static void Main()
 {
     using (Socket listeningSocket = new Socket(AddressFamily.InterNetwork,
                                                SocketType.Stream,
                                                ProtocolType.Tcp))
     {
         listeningSocket.Bind(new IPEndPoint(IPAddress.Any, port));
         Debug.Print("Listening for a client...");
         listeningSocket.Listen(1);
         using (Socket communicationSocket = listeningSocket.Accept())
         {
             Debug.Print("Connected to client.");
             using (SslStream sslStream = new SslStream(communicationSocket))
             {
                 X509Certificate serverCert =
                      new X509Certificate(Resources.GetBytes(Resources.BinaryResources.MyServer));
                 X509Certificate rootCA =
                      new X509Certificate(Resources.GetBytes(Resources.BinaryResources.MyRootCA));
                 sslStream.AuthenticateAsServer(serverCert, // To authenticate the server
                                                new X509Certificate[] { rootCA }, // CA certificates
                                                SslVerification.CertificateRequired, // Verify client
                                                SslProtocols.Default // Protocols that may be used
                                                );
                 //wait infinitely to get a response
                 sslStream.ReadTimeout = -1;
                 byte[] inBuffer = new byte[1000];
                 int count = sslStream.Read(inBuffer, 0, inBuffer.Length);
                 string message = new string(Encoding.UTF8.GetChars(inBuffer));
                 Debug.Print("Received '" + message + "'.");
             }
         }
     }
 }
开发者ID:meikeric,项目名称:DotCopter,代码行数:33,代码来源:Program.cs

示例7: ListenThreadFunc

        void ListenThreadFunc()
        {
            Socket listenSocket = null;
            try
            {
                listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPEndPoint ep = new IPEndPoint(IPAddress.Any, _port);
                listenSocket.Bind(ep);
                LogThread.Log("ListenThread: Listening on port " + _port, LogThread.LogMessageType.Normal, true);

                while (true)
                {
                    listenSocket.Listen(10);
                    Socket conn = listenSocket.Accept();
                    if (conn != null && OnConnectionAccepted != null)
                    {
                        LogThread.Log("ListenThread: Connection Accepted", LogThread.LogMessageType.Debug);
                        OnConnectionAccepted(this, new SocketArg(conn));
                    }
                }
            }
            catch (Exception ex)
            {
                LogThread.Log(ex.ToString(), LogThread.LogMessageType.Error, true);

                listenSocket.Close();
                _theThread = null;
            }
        }
开发者ID:acid1789,项目名称:DecoServer2,代码行数:29,代码来源:ListenThread.cs

示例8: Signaler

        public Signaler()
        {
            m_dummy = new byte[] { 0 };
            m_receiveDummy = new byte[1];

            //  Create the socketpair for signaling.
            using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Unspecified))
            {
                listener.NoDelay = true;
                listener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

                // using ephemeral port
                listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
                listener.Listen(1);

                m_writeSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Unspecified);
                m_writeSocket.NoDelay = true;

                m_writeSocket.Connect(listener.LocalEndPoint);
                m_readSocket = listener.Accept();
            }

            m_writeSocket.Blocking = false;
            m_readSocket.Blocking = false;
        }
开发者ID:bbqchickenrobot,项目名称:netmq,代码行数:25,代码来源:Signaler.cs

示例9: Listen

        //-------------------------------------------------------------------------------------------
        public void Listen(string ipaddress, int port)
        {
            IPEndPoint ipendpoint	= new IPEndPoint(IPAddress.Parse(ipaddress), port);
            Socket Listener		= new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            listenersocket			= Listener;
            try
            {
                Listener.Bind(ipendpoint);
                Listener.Listen((int) SocketOptionName.MaxConnections);

                DebugOut("Listening on: " + Listener.LocalEndPoint.ToString(), false);
            }
            catch(Exception e)
            {
                DebugOut("Failed to bind: " + e.Message, true);
                return;
            }

            while (!Listening && !Environment.HasShutdownStarted)
            {
                try
                {
                    ThreadPool.QueueUserWorkItem(_OnAccept, Listener.Accept());
                }
                catch
                {
                    Thread.Sleep(100);
                }
            }

            Listener.Shutdown(SocketShutdown.Both);
            Listener.Close();
        }
开发者ID:weavver,项目名称:net,代码行数:34,代码来源:SocketServer.cs

示例10: Main

        static void Main()
        {
            // I'm going to listen for any incoming requests on this machine so I need to find out
            // what my address is. An empty string tells it to get the address of this machine
            var ipAddr = Dns.GetHostAddresses("")[0];

            // create a server socket, its only purpose is to listen for connections
            // and to create client sockets to handle requests
            // going to use TCP to communicate
            var server = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            // the server will be located on port 4510 on this machine
            server.Bind(new IPEndPoint(ipAddr, 4510));

            // start listening and allow for a backlog of 10 request between our accepts
            server.Listen(10);

            Console.WriteLine("Waiting to get asked the time");

            while (true)
            {
                // Wait for a client to connect, Accept is blocking
                // request is a client socket and will be used for this piece of communication
                var client = server.Accept();

                Console.WriteLine("Connection accepted");

                Task.Factory.StartNew(() => Chat(client));
            }
        }
开发者ID:JohnBrod,项目名称:TalkingClock,代码行数:30,代码来源:Program.cs

示例11: Main

        static void Main(string[] args)
        {
            byte[] bytes = new Byte[1024];

            // Establish the local endpoint for the socket.
            // Dns.GetHostName returns the name of the
            // host running the application.
             string serverIP = args[0];// "192.168.56.1";
             IPAddress ipAddress = IPAddress.Parse(serverIP);
             IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 1010);

            // Create a TCP/IP socket.
            Socket listener = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
            Console.WriteLine("This is a Server ");
            // 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("Server: Waiting for a connection...");
                    // Program is suspended while waiting for an incoming connection.
                    Socket handler = listener.Accept();
                    string data = null;
                    // An incoming connection needs to be processed.
                        bytes = new byte[1024];
                        while (true)
                        {

                            int bytesRec = handler.Receive(bytes);
                            data = Encoding.ASCII.GetString(bytes, 0, bytesRec);
                            if (data.IndexOf("<EOF>") > -1)
                            {
                                Console.WriteLine("Client is done sending all the text");
                                break;
                            }
                            if (bytesRec == 0)
                            {
                                continue;
                            }
                            else
                            {
                                Console.WriteLine("Text received from client: " + data);
                                bytesRec = 0;
                                data = "";
                            }
                        }
                        handler.Shutdown(SocketShutdown.Both);
                        handler.Close();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            Console.Read();
        }
开发者ID:c0deForLife,项目名称:Socket_Passing,代码行数:60,代码来源:Server.cs

示例12: ServerListen

        private void ServerListen()
        {
            Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            serverSocket.Bind(new IPEndPoint(IPAddress.Any, localPort));
            serverSocket.Listen(1);

            while (true)
            {
                try
                {
                    Socket clientSocket = serverSocket.Accept();
                    using (NetworkStream stream = new NetworkStream(clientSocket))
                    {
                        var request = ReadRequest(stream);
                        OnNewCmdReceived(request);

                        stream.Close();
                    }

                    clientSocket.Close();
                }
                catch (Exception ex)
                {
                    Logger.AddError("Failed to process connection", ex);
                }
            }
        }
开发者ID:intech,项目名称:Checker,代码行数:27,代码来源:CommandReader.cs

示例13: Main

        static void Main(string[] args)
        {
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint address = new IPEndPoint(IPAddress.Any, 8080);
            socket.Bind(address);
            socket.Listen(10);
            //int i = 0;
            //int N = 2;
            //Socket[] clients = new Socket[N];
            while (true)
            {
                Socket client = socket.Accept();

                String template = "HTTP/1.1 200 OK\r\n" +
                                  "Server: NataServer\r\n" +
                                  "Content-Type: text/plain; charset=UTF-8\r\n" +
                                  "Content-Length: {0}\r\n" +
                                  "\r\n" +
                                  "{1}";
                String s = DateTime.Now.ToString();
                String answer = String.Format(template, s.Length, s);
                Console.WriteLine(answer);
                byte[] msg = Encoding.UTF8.GetBytes(answer);
                client.Send(msg);

                client.Shutdown(SocketShutdown.Both);
                client.Close();
            }
        }
开发者ID:AlienaAngel,项目名称:PSP,代码行数:29,代码来源:Program.cs

示例14: StartConnection

        /// <summary>
        /// 启动等待连接
        /// </summary>
        public void StartConnection()
        {
            serverListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);  // Start the socket

            string[] ip = WebSocketProtocol.GetInstance.ServerId.Split('.');
            IPAddress localIp = new IPAddress(new byte[] { Convert.ToByte(ip[0]), Convert.ToByte(ip[1]), Convert.ToByte(ip[2]), Convert.ToByte(ip[3]) });
            serverListener.Bind(new IPEndPoint(localIp, WebSocketProtocol.GetInstance.ServerPort));

            serverListener.Listen(WebSocketProtocol.GetInstance.ConnectionsCount);
            while (true)
            {
                //等待客户端请求
                Socket sc = serverListener.Accept();
                if (sc != null)
                {
                    Thread.Sleep(100);
                    ClientSocketInstance ci = new ClientSocketInstance();
                    ci.ClientSocket = sc;
                    //初始化三个事件
                    ci.NewUserConnection += new ClientSocketEvent(Ci_NewUserConnection);
                    ci.ReceiveData += new ClientSocketEvent(Ci_ReceiveData);
                    ci.DisConnection += new ClientSocketEvent(Ci_DisConnection);
                    //开始与客户端握手[握手成功,即可通讯了]
                    ci.ClientSocket.BeginReceive(ci.receivedDataBuffer, 0, ci.receivedDataBuffer.Length, 0, new AsyncCallback(ci.StartHandshake), ci.ClientSocket.Available);
                    listConnection.Add(ci);

                }

            }
        }
开发者ID:cpm2710,项目名称:cellbank,代码行数:33,代码来源:WebSocketServer.cs

示例15: Main

        public static void Main()
        {
            var networkInterface = NetworkInterface.GetAllNetworkInterfaces()[0];

            Debug.Print(networkInterface.IPAddress.ToString());
            //networkInterface.IsDynamicDnsEnabled = false;
            //
            networkInterface.EnableStaticIP("192.168.1.200", "255.255.255.0", "192.168.1.1");
            using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                socket.Bind(new IPEndPoint(IPAddress.Any, 5230));
                socket.Listen(1);

                while (true)
                {
                    using (var client = socket.Accept())
                    {
                        //new Thread(() =>
                        //{
                            var clientActive = true;

                            while (clientActive)
                            {
                                //var buffer = new byte[5];
                                //client.Receive(buffer);
                                var buffer = client.Receive(5);
                                Interpret(buffer, client);
                            }
                        //}).Start();
                    }
                }
            }
        }
开发者ID:John-Leitch,项目名称:Blue-Racer-CPU,代码行数:33,代码来源:Program.cs


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