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


C# TcpListener.AcceptSocket方法代码示例

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


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

示例1: connect

 //Connect to the client
 public void connect()
 {
     if (!clientConnected)
     {
         IPAddress ipAddress = IPAddress.Any;
         TcpListener listener = new TcpListener(ipAddress, portSend);
         listener.Start();
         Console.WriteLine("Server is running");
         Console.WriteLine("Listening on port " + portSend);
         Console.WriteLine("Waiting for connections...");
         while (!clientConnected)
         {
             s = listener.AcceptSocket();
             s.SendBufferSize = 256000;
             Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
             byte[] b = new byte[65535];
             int k = s.Receive(b);
             ASCIIEncoding enc = new ASCIIEncoding();
             Console.WriteLine("Received:" + enc.GetString(b, 0, k) + "..");
             //Ensure the client is who we want
             if (enc.GetString(b, 0, k) == "hello" || enc.GetString(b, 0, k) == "hellorcomplete")
             {
                 clientConnected = true;
                 Console.WriteLine(enc.GetString(b, 0, k));
             }
         }
     }
 }
开发者ID:kartikeyadubey,项目名称:share,代码行数:29,代码来源:Server.cs

示例2: StartListening

        public void StartListening()
        {
            R = RowacCore.R;
            R.Log("[Listener] Starting TCP listener...");
            TcpListener listener = new TcpListener(IPAddress.Any, 28165);
            listener.Start();

            while (true)
            {
                try
                {
                    var client = listener.AcceptSocket();
            #if DEBUG
                    R.Log("[Listener] Connection accepted.");
            #endif

                    var childSocketThread = new Thread(() =>
                    {
                        byte[] data = new byte[1048576]; // for screenshots and tasklists
                        int size = 0;
                        while (client.Available != 0)
                            size += client.Receive(data, size, 256, SocketFlags.None); // TODO: increase reading rate from 256?
                        client.Close();

                        string request = Encoding.ASCII.GetString(data, 0, size);
            #if DEBUG
                        R.Log(string.Format("Received [{0}]: {1}", size, request));
            #endif
                        ParseRequest(request);
                    });
                    childSocketThread.Start();
                }
                catch (Exception ex) { R.LogEx("ListenerLoop", ex); }
            }
        }
开发者ID:Riketta,项目名称:rust-anticheat,代码行数:35,代码来源:Server.cs

示例3: Run

        //Clienter der kan tilkoble serveren
        private void Run()
        {
            string productInformation = Console.ReadLine();

            try
            {
                string[] splitProduct = productInformation.Split('|');
                _product = new Product(splitProduct[0], double.Parse(splitProduct[1]), splitProduct[2]);
                Console.WriteLine("[" + GetDatetime() + "] Server: Produktet er blevet oprettet");
            }
            catch (Exception)
            {
                Console.WriteLine("[" + GetDatetime() + "] Server: Du har indtastet produktet i et ugyldigt format! Prøv igen.");
                Run();
            }

            TcpListener _tcpListener = new TcpListener(IPAddress.Any, _port);
            _tcpListener.Start();

            while (true)
            {
                Socket socket = _tcpListener.AcceptSocket();
                _clientIP = socket.RemoteEndPoint as IPEndPoint;

                Console.WriteLine("[" + GetDatetime() + "] Server: {0} er forbundet til serveren.", _clientIP.Address);
                ClientHandler clientHandler = new ClientHandler(socket, _product, _service, _clientIP);
                Thread clientThread = new Thread(clientHandler.Run);
                clientThread.Start();
            }
        }
开发者ID:MrCaira,项目名称:PowerRangers_AuctionHouse_2014,代码行数:31,代码来源:Server.cs

示例4: Main1

        public static void Main1(string[] args)
        {
            string name = "localhost";
            IPAddress[] addrs = Dns.GetHostEntry(name).AddressList;

            Console.WriteLine(addrs[0]);
            Console.WriteLine(addrs[1]);

            //TcpListener welcomeSocket = new TcpListener(addrs[1], 6789);
            //IPAddress ip = IPAddress.Parse("127.0.0.1");
            //TcpListener serverSocket = new TcpListener(ip, 6789);

            TcpListener serverSocket = new TcpListener(6789);
            serverSocket.Start();

            while (true)
            {
                Socket connectionSocket = serverSocket.AcceptSocket();
                Console.WriteLine("Server activated now");
                WebServerhelper service = new WebServerhelper(connectionSocket);
                service.DoIt();

            }

            serverSocket.Stop();
        }
开发者ID:Rony0292,项目名称:httpserver2014,代码行数:26,代码来源:WebServerhelper.cs

示例5: BackupProcess

        static void BackupProcess()
        {
            Console.WriteLine("I am backup!");
            
            IPAddress ipAddress = Dns.GetHostEntry("localhost").AddressList[0];
            TcpListener listener = new TcpListener(ipAddress, port);
            listener.Start();
            Socket sock = listener.AcceptSocket();
            Stream str = new NetworkStream(sock);
            StreamReader sr = new StreamReader(str);

            string line = "-1";

            try
            {
                while (true)
                    line = sr.ReadLine();
            }
            catch(IOException)
            { 
                sr.Close();
                listener.Stop();

                PrimaryProcess(Convert.ToInt32(line) + 1);
            }
        }
开发者ID:DanglingPointer,项目名称:TTK4145,代码行数:26,代码来源:Program.cs

示例6: Main

        static void Main(string[] args)
        {
            var settings = ConfigurationManager.AppSettings;
            var port = settings["COM_PORT"];
            var speed = Convert.ToInt32(settings["COM_SPEED"]);
            var tcpPort = Convert.ToInt32(settings["TCP_PORT"]);
            serial = new SerialManager(port, speed);
            Console.WriteLine("UART: " + port + " - " + speed);
            server = new HardwareTcpServer(tcpPort);
            server.OnServerState += server_OnServerState;
            server.OnClientState += server_OnClientState;
            server.OnData += server_OnData;
            serial.OnReceive += serial_OnReceive;
            serial.OnStateChange += serial_OnStateChange;
            serial.Connect();

           // bridge = new HttpToUartBridge(6200);

            TcpListener listener = new TcpListener(IPAddress.Parse("188.127.233.35"), tcpPort);
            listener.Start();
            Console.WriteLine("TCP: " + tcpPort);
            while (Thread.CurrentThread.ThreadState == ThreadState.Running)
            {
                Console.WriteLine("Listening " + tcpPort);
                while (!listener.Pending())
                {
                    Thread.Sleep(300);
                }
                server.AcceptTcpClient(listener.AcceptSocket());
            }
            Console.WriteLine("Stopped");
            listener.Stop();
            server.Close();
            serial.Close();
        }
开发者ID:WebManufacture,项目名称:Legacy.NET,代码行数:35,代码来源:Program.cs

示例7: BeginLister

 public void BeginLister()
 {
     while (true)
     {
         try
         {
             IPAddress[] Ips = Dns.GetHostAddresses("");
             string GetIp = Ips[0].ToString();
             Listener = new TcpListener(IPAddress .Parse (GetIp ),8888);
             Listener.Start();
             CheckForIllegalCrossThreadCalls = false;
             butBeginSever.Enabled = false;
             this.Text = "服务器已经开启.....";
             SocketClient = Listener.AcceptSocket();
             NetStream = new NetworkStream(SocketClient );
             ServerWriter = new StreamWriter(NetStream );
             ServerReader = new StreamReader(NetStream );
             if (SocketClient.Connected)
             {
                 MessageBox.Show("客户端连接成功!","服务器消息",MessageBoxButtons .OK ,MessageBoxIcon.Information );
             }
         }
         catch { }
     }
 }
开发者ID:mayifighting,项目名称:.net,代码行数:25,代码来源:Form1.cs

示例8: ShowUsage

        public override void ShowUsage()
        {
            //NetWorkStream类是专门用来处理服务器与客户端通信的流。它在网络编程中经常使用,主要是用来处理类似Socket、TcpClient和TcpListener这些类中得到的流。
            //服务器端
            TcpListener lis = new TcpListener(5000);                        //服务器监听
            lis.Start();//启动
            Socket sock = lis.AcceptSocket();                               //阻塞,直到有客户端连接

            NetworkStream netStream = new NetworkStream(sock);              //得到Socket中的流
            if (netStream.DataAvailable)                                    //如果客户端发送了消息
            {
                byte[] data = new byte[1024];                               //定义一个字节数组,用来存放接收的数据
                int len = netStream.Read(data, 0, data.Length);             //从位置开始,读取到字节数组末尾
                string line = Encoding.Default.GetString(data, 0, len);     //把收到的字节转换为字符串
            }

            //客户端
            TcpClient client = new TcpClient();                             //客户端tcp对象
            client.Connect("127.0.0.1", 5000);                              //连接服务器
            NetworkStream myStream = client.GetStream();                    //得到网络流

            byte[] data2 = Encoding.Default.GetBytes("Hi,你好");           //首先把输入的字符串消息转换为字节
            myStream.Write(data2, 0, data2.Length);                         //向myStream 里写入数据
            myStream.Flush();                                               //刷新流中的数据
            myStream.Close();
        }
开发者ID:BerdyPango,项目名称:Researches,代码行数:26,代码来源:NetWorkStreamUsage.cs

示例9: StartClientServer

        public void StartClientServer(String ip, int port)
        {
            string ipString = ip.ToString();
            // Parse client ip address
            IPAddress ipaddress = IPAddress.Parse(ipString);  // Format exception

            // Initialize client listener
            listener = new TcpListener(ipaddress, port);

            // Set loop variable
            Boolean loop = true;
            try
            {
                // Start listening on client port
                listener.Start();

                while (loop)
                {
                    Socket newClient = listener.AcceptSocket();
                    ClientThreadHandler cth = new ClientThreadHandler(newClient);
                    cth.StartHandling();
                }
            }catch(Exception error)
            {
                MessageBox.Show(error.Message);
            }
        }
开发者ID:Ikthios,项目名称:P2P,代码行数:27,代码来源:ClientCore.cs

示例10: Start

        /// <summary>
        /// Start the listener for incoming messages
        /// </summary>
        public void Start()
        {
            tcpListener = new TcpListener(System.Net.IPAddress.Any, this.port);
            tcpListener.Start();
            Console.WriteLine("Server Started") ;
            this.IsListening = true;

            try
            {
                while (isListening)
                {
                    Console.WriteLine("Server listening...");
                    Socket socketForClient = tcpListener.AcceptSocket();
                    Console.WriteLine("Client connected");
                    NetworkStream networkStream = new NetworkStream(socketForClient);

                    BinaryFormatter bf = new BinaryFormatter();
                    Object message = (RemoteMessage)bf.Deserialize(networkStream);

                    networkStream.Flush();

                    interpretMessage((RemoteMessage)message);

                    socketForClient.Disconnect(true);
                }
            }
            catch(Exception e)
            {
                Console.WriteLine(e.ToString()) ;
            }
        }
开发者ID:psweeney-YU,项目名称:NEVP-conveyor,代码行数:34,代码来源:RemoteServer.cs

示例11: SendFile

        public void SendFile(string fileName)
        {
            tcpListener2 = new TcpListener(LocalAddress,PORT_SEND);
            tcpListener2.Start();

            while(true)
            {
                Socket socket  = tcpListener2.AcceptSocket();

                NetworkStream netStream = new NetworkStream(socket);
                StreamWriter sWriter = new StreamWriter(netStream);

                string Path="E:/" + fileName;
                FileInfo File = new FileInfo(Path);
                if (list_Files.Contains(fileName)&&fileName=="Quit") break;
                list_Files.Add(fileName);
                filePath= "E:/" + fileName;
                FileStream InputFile = new FileStream(filePath, FileMode.CreateNew, FileAccess.Write, FileShare.None);
                BinaryWriter BinaryStream = new BinaryWriter(InputFile);
                byte[] data = new byte[BUFFER];
                do
                {
                    socket.Receive(data);
                    BinaryStream.Write(data);

                } while (data.Length != 0);
                BinaryStream.Flush();
                BinaryStream.Close();
                InputFile.Close();

            }
        }
开发者ID:khanhduy94,项目名称:TestCayCu,代码行数:32,代码来源:Form1.cs

示例12: listenClient

        public void listenClient()
        {
            LocalAddress = IPAddress.Parse("127.0.0.1");
            tcpListener = new TcpListener(LocalAddress,PORT_RECEIVE);
            tcpListener.Start();

            while(true)
            {
                Socket socket = tcpListener.AcceptSocket();
                NetworkStream netStream = new NetworkStream(socket);
                StreamReader sReader = new StreamReader(netStream);
                fileName = sReader.ReadLine();
                if (list_Files.Contains(fileName)&&fileName=="Quit") break;
                list_Files.Add(fileName);
                string Path="E:/" + fileName;
                FileStream InputFile = new FileStream(Path, FileMode.CreateNew, FileAccess.Write, FileShare.None);
                BinaryWriter BinaryStream = new BinaryWriter(InputFile);
                byte[] data = new byte[BUFFER];
                do
                {
                    socket.Receive(data);
                    BinaryStream.Write(data);

                } while (data.Length != 0);
                BinaryStream.Flush();
                BinaryStream.Close();
                InputFile.Close();

            }
        }
开发者ID:khanhduy94,项目名称:TestCayCu,代码行数:30,代码来源:Form1.cs

示例13: Main

        static void Main(string[] args)
        {
            LinkedList<Client> listeClient = new LinkedList<Client>();

            int port = 6666;

            //on se déclare une oreille TCP sur un port spécifique
            TcpListener serveur = new TcpListener(System.Net.IPAddress.Any,port);

            //on la démarre....
            serveur.Start();

            //tant que le serveur est en vie on tourne en rond
            while (true)
            {
                Console.WriteLine(">> On attend une connexion");
                // cette ligne bloque tant que l'oreille n'entends pas une connexion
                Socket socketClient = serveur.AcceptSocket();

                Client client = new Client(socketClient,listeClient);

                ThreadStart ts = new ThreadStart(client.Thread);
                Thread trd = new Thread(ts);
                trd.Start();
            }
        }
开发者ID:ExpoSAT-2014-NAO-Kinect,项目名称:Chat2NAO,代码行数:26,代码来源:Program.cs

示例14: WebServer

        public WebServer(int port, string root)
        {
            /* this script processor instance will be used to process files of type
             * csscript */
            _scriptProcessor = new CscriptProcessor();

            /*TODO: add another instance of a IScriptProcessor to handle files of
             * type csweb */
            _webTemplateProcessor = new CWebTemplateProcessor();

            /* set the root for the server */
            _webRoot = root;

            /* create a TcpListener to listen for netweork requests on the provided
             * port number at the lookedup host address and start listening */
            TcpListener listener = new TcpListener(
                Dns.GetHostAddresses("localhost")[0], port);
            listener.Start();
            Console.WriteLine("Web server listening on port {0}", port);

            /* main body of the web server, this will listen for requests,
             * open a socket with the client when a request is received
             * and spawn a process thread for accepting the request and
             * return to listen for the next request */
            while (true)
            {
                Socket soc = listener.AcceptSocket();
                new Task(delegate()
                {
                    AcceptRequest(soc);
                }).Start();
            }
        }
开发者ID:Rumel,项目名称:SimpleWebServer,代码行数:33,代码来源:WebServer.cs

示例15: Main

        static void Main(string[] args)
        {
            try
            {
                tcpListener = new TcpListener(IPAddress.Any, 100);
                tcpListener.Start();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Could not start the server on Port 100:");
                Console.WriteLine(ex.Message);
                Console.ReadLine();
                Environment.Exit(-1);
            }

            try
            {
                while (true)
                {
                    new Thread(new Client(tcpListener.AcceptSocket()).Start).Start();
                    Console.WriteLine("New Player connected");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Could not listen on Port 100:");
                Console.WriteLine(ex.Message);
                Console.ReadLine();
                Environment.Exit(-1);
            }
        }
开发者ID:bluemangoentertainment,项目名称:Retarded2_Old,代码行数:31,代码来源:Program.cs


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