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


C# Socket.Shutdown方法代码示例

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


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

示例1: Main

        static void Main(string[] args)
        {
            byte[] receiveBytes = new byte[1024];
            int port =8080;//服务器端口
            string host = "10.3.0.1";  //服务器ip
            
            IPAddress ip = IPAddress.Parse(host);
            IPEndPoint ipe = new IPEndPoint(ip, port);//把ip和端口转化为IPEndPoint实例 
            Console.WriteLine("Starting Creating Socket Object");
            Socket sender = new Socket(AddressFamily.InterNetwork, 
                                        SocketType.Stream, 
                                        ProtocolType.Tcp);//创建一个Socket 
            sender.Connect(ipe);//连接到服务器 
            string sendingMessage = "Hello World!";
            byte[] forwardingMessage = Encoding.ASCII.GetBytes(sendingMessage + "[FINAL]");
            sender.Send(forwardingMessage);
            int totalBytesReceived = sender.Receive(receiveBytes);
            Console.WriteLine("Message provided from server: {0}",
                              Encoding.ASCII.GetString(receiveBytes,0,totalBytesReceived));
            //byte[] bs = Encoding.ASCII.GetBytes(sendStr);

            sender.Shutdown(SocketShutdown.Both);  
            sender.Close();
            Console.ReadLine();
        }
开发者ID:qychen,项目名称:AprvSys,代码行数:25,代码来源:ClientCode.cs

示例2: Begin

        private Socket SOCKET; //receive socket

        #endregion Fields

        #region Methods

        public void Begin()
        {
            connect:
            SOCKET = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            SOCKET.Connect(IPAddress.Parse("127.0.0.1"), 2404);
            Console.WriteLine("S104 establish a link successfully, try to receive...");

            RCV_THREAD = new System.Threading.Thread(BeginReceive);
            RCV_THREAD.Start(SOCKET);

            while (true)
            {
                System.Threading.Thread.Sleep(4000);
                this.Send_UFram(Uflag.testfr_active);
                if (RCVD_NUM >= 20000)
                {
                    SOCKET.Shutdown(SocketShutdown.Receive);
                    RCV_THREAD.Abort();
                    System.Threading.Thread.Sleep(4000);
                    SOCKET.Shutdown(SocketShutdown.Send);
                    SOCKET.Dispose();

                    RCVD_NUM = 0;
                    goto connect;
                }
                if (DateTime.Now - lastTime > new TimeSpan(0, 0, 4))
                {
                    this.Send_SFram(RCVD_NUM);
                    Console.WriteLine("overtime send S fram...");
                }
            }
        }
开发者ID:Wave-Maker,项目名称:S104,代码行数:38,代码来源:S104.cs

示例3: ClientCreateSendAndReceive

        private byte[] ClientCreateSendAndReceive(byte[] dataToSend)
        {
            var bufferSize = 512;
            var buffer = new byte[bufferSize];

            var socket = new Socket(_serverAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            socket.Connect(_serverAddress);

            socket.Send(dataToSend);
            socket.Shutdown(SocketShutdown.Send);

            using (var memory = new MemoryStream(bufferSize))
            {
                int bytesRec;
                while ((bytesRec = socket.Receive(buffer)) > 0)
                {
                    memory.Write(buffer, 0, bytesRec);
                }

                socket.Shutdown(SocketShutdown.Receive);
                socket.Close();
                buffer = memory.ToArray();
            }
            return buffer;
        }
开发者ID:progala2,项目名称:DVRP,代码行数:25,代码来源:TcpServerTests.cs

示例4: LinkEQP

        private string gsProgrammerMail = ConfigurationManager.AppSettings.Get("ProgrammerMail"); //從AppConfig讀取「ProgrammerMail」參數

        #endregion Fields

        #region Methods

        /// <summary>
        /// 連線或斷線至ModBusToEthernet設備
        /// iStatus = 0,則連線
        /// iStatus = 1,則斷線
        /// </summary>
        /// <param name="iStatus">0為連線、1為斷線</param>
        /// <param name="sIP">設備的IP位址</param>
        /// <param name="sIPPort">設備的IP_Port</param>
        public bool LinkEQP(int iStatus, string sIP, string sIPPort, Socket gWorkSocket)
        {
            bool blFlag = false;
            try
            {
                switch (iStatus)
                {
                    case 0:
                        // Set the timeout for synchronous receive methods to
                        // 1 second (1000 milliseconds.)
                        gWorkSocket.ReceiveTimeout = giReceiveTimeout * 1000;

                        // Set the timeout for synchronous send methods
                        // to 1 second (1000 milliseconds.)
                        gWorkSocket.SendTimeout = giSendTimeout * 1000;

                        if (gWorkSocket.Connected == true)
                        {
                            gWorkSocket.Shutdown(SocketShutdown.Both);
                            gWorkSocket.Close();
                        }
                        else if (gWorkSocket.Connected == false)
                        {
                            gWorkSocket.Connect(sIP, Convert.ToInt32(sIPPort));
                            if ((gWorkSocket.Connected == true))
                            {
                                //System.Threading.Thread.Sleep(150);
                                gLogger.Trace("ModbusRTU--成功連結 to:" + sIP);
                            }
                        }
                        blFlag = true;
                        break;
                    case 1:
                        if ((gWorkSocket.Connected == true))
                        {
                            gWorkSocket.Shutdown(SocketShutdown.Both);
                            gWorkSocket.Close();
                            //System.Threading.Thread.Sleep(150);
                            gLogger.Trace("ModbusRTU--取消連線 to:" + sIP);
                        }
                        blFlag = false;
                        break;
                }
            }
            catch (Exception ex)
            {
                gLogger.ErrorException("ModbusTCP.LinkEQP:", ex);
                if (gWorkSocket.Connected)
                {
                    gWorkSocket.Shutdown(SocketShutdown.Both);
                    gWorkSocket.Close();
                }
                throw ex;
            }
            return blFlag;
        }
开发者ID:FTCEEP,项目名称:CGUST,代码行数:70,代码来源:SocketLink.cs

示例5: StartClient

        public static void StartClient(string ip, string data)
        {
            // Data buffer for incoming data.
            byte[] bytes = new byte[1024];

            // Connect to a remote device.
            try
            {
                // Establish the remote endpoint for the socket.
                // This example uses port 11000 on the local computer.
                IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
                IPAddress ipAddress = IPAddress.Parse(ip);
                IPEndPoint remoteEP = new IPEndPoint(ipAddress, 15001);

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

                // Connect the socket to the remote endpoint. Catch any errors.
                try
                {
                    sender.Connect(remoteEP);

                    Console.WriteLine("Socket connected to {0}",
                        sender.RemoteEndPoint.ToString());

                    // Encode the data string into a byte array.
                    byte[] msg = Encoding.ASCII.GetBytes(data + "<EOF>");

                    // Send the data through the socket.
                    int bytesSent = sender.Send(msg);

                    // Receive the response from the remote device.
                    int bytesRec = sender.Receive(bytes);
                    Console.WriteLine("Echoed test = {0}",
                        Encoding.ASCII.GetString(bytes, 0, bytesRec));

                    // Release the socket.
                    sender.Shutdown(SocketShutdown.Both);
                    sender.Close();
                    Console.WriteLine("finish " + DateTime.Now);
                }
                catch (Exception e)
                {
                    sender.Shutdown(SocketShutdown.Both);
                    sender.Close();
                    Console.WriteLine("Unexpected exception : {0}", e.ToString());
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
开发者ID:rbarber8,项目名称:historical_curve,代码行数:55,代码来源:sclient.cs

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

示例7: Main

        static void Main(string[] args)
        {
            byte[] receiveBytes = new byte[1024];
            //解析域名或者IP
            IPHostEntry ipHost = Dns.GetHostEntry("127.0.0.1");
            //获取与主机关联的IP地址列表
            IPAddress ipAddress = ipHost.AddressList[3];
            //IP地址和端口号连接为一个节点
            IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 8008);
            Console.WriteLine("Starting: 创建 Socket 对象");

            //创建发送socket实例
            Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //建立远程主机连接
            sender.Connect(ipEndPoint);
            Console.WriteLine("成功连接到:{0}", sender.RemoteEndPoint);

            string sendingMessage = "Hello my first socket test";
            Console.WriteLine("信息:{0}", sendingMessage);
            byte[] forwardMessage = Encoding.ASCII.GetBytes(sendingMessage + "[FINAL]");
            // 将数据发送到连接的Socket
            sender.Send(forwardMessage);
            //接受数据,写入缓冲区
            int totalBytesRecevied = sender.Receive(receiveBytes);
            Console.WriteLine("准备从服务端接受信息:{0}", Encoding.ASCII.GetString(receiveBytes, 0, totalBytesRecevied));
            sender.Shutdown(SocketShutdown.Both);
            sender.Close();
            Console.ReadLine();
        }
开发者ID:Joozo,项目名称:LearningDemo,代码行数:29,代码来源:Program.cs

示例8: disconnect

 public bool disconnect(Socket soc)
 {
     // Release the socket.
     soc.Shutdown(SocketShutdown.Both);
     soc.Close();
     return true;
 }
开发者ID:hangmiao,项目名称:DBLike,代码行数:7,代码来源:Connection.cs

示例9: stopMainThread

        /*
         * Stops the server thread
         */
        public void stopMainThread()
        {
            if (thread.IsAlive == true)
            {
                // Establish the remote endpoint for the socket.
                IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
                IPAddress ipAddress = ipHostInfo.AddressList[0];
                IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11001);

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

                // Connect the socket to the remote endpoint. Catch any errors.
                try
                {
                    stop = true;
                    snder.Connect(remoteEP);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                snder.Shutdown(SocketShutdown.Both);
                snder.Close();
                // Abort watchdog thread also
                if (watchdog.IsAlive == true)
                {
                    watchdog.Abort();
                }
            }
            else
            {
                Application.Exit();
            }
        }
开发者ID:ravjotsingh9,项目名称:StockTradingApplication,代码行数:38,代码来源:ServerMainThread.cs

示例10: Connect

        public void Connect(string message)
        {
            // Connect to a remote device.
            try
            {
                var ipHostInfo = Dns.Resolve(Dns.GetHostName());
                IPAddress ipAddress = ipHostInfo.AddressList[0];
                IPEndPoint remoteEP = new IPEndPoint(ipAddress, 12000);

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

                // Connect to the remote endpoint.
                client.BeginConnect(remoteEP, ConnectCallback, client);
                connectDone.WaitOne();

                // Send test data to the remote device.
                Send(client, message);
                sendDone.WaitOne();

                // Receive the response from the remote device.
                Receive(client);
                receiveDone.WaitOne();

                // Release the socket.
                client.Shutdown(SocketShutdown.Both);
                client.Close();

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
开发者ID:jmptrader,项目名称:Switch-Transaccional,代码行数:33,代码来源:SocketHandler.cs

示例11: SendMessage

        static void SendMessage(int port)
        {
            byte[] bytes = new byte[1024];

            IPAddress ipAddr = IPAddress.Parse("10.7.5.10");
            //IPHostEntry ipHost = Dns.GetHostEntry("localhost");
            //IPAddress ipAddr = ipHost.AddressList[0];
            IPEndPoint ipEnd = new IPEndPoint(ipAddr, port);

            Socket sSender = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            sSender.Connect(ipEnd);

            Console.WriteLine("Enter your message:");
            string message = Console.ReadLine();

            Console.WriteLine("Client connect with {0}", sSender.RemoteEndPoint.ToString());
            byte[] msg = Encoding.UTF8.GetBytes(message);

            int bytesSend = sSender.Send(msg);
            int bytesRec = sSender.Receive(bytes);

            Console.WriteLine("Answer from server : {0}", Encoding.UTF8.GetString(bytes,0,bytesRec));

            if (message.IndexOf("<TheEnd>") == -1)
                SendMessage(port);

            sSender.Shutdown(SocketShutdown.Both);
            sSender.Close();
        }
开发者ID:vadimvoyevoda,项目名称:NetworkProgramming,代码行数:30,代码来源:Program.cs

示例12: Main

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

            // Idea terrible usar SaveFileDialog en una aplicación de consola
            // Hecho solo con propósitos educativos:
            using (OpenFileDialog fileDialog = new OpenFileDialog())
            {
                fileDialog.Multiselect = true;
                if (fileDialog.ShowDialog() == DialogResult.OK)
                {
                    IPEndPoint remotePoint = new IPEndPoint(IPAddress.Loopback, 4040);
                    Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    s.Connect(remotePoint);
                    FileWriter sw = new FileWriter(s);

                    sw.WriteInt32(fileDialog.FileNames.Count());
                    for (int i = 0; i < fileDialog.FileNames.Count(); i++)
                    {
                        sw.WriteString(Path.GetFileName(fileDialog.FileNames[i]));
                        sw.WriteFile(fileDialog.FileNames[i]);
                    }

                    s.Shutdown(SocketShutdown.Both);
                    s.Close();

                }
                Console.Read();
            }
        }
开发者ID:rokerdan,项目名称:aplicaciones-redes,代码行数:30,代码来源:Program.cs

示例13: Beta

        //public void Beta(IPAddress target, int port)
        public void Beta()
        {
            IPAddress target = IPAddress.Parse("192.168.1.1");
            IPEndPoint remote = new IPEndPoint(target, 22);
            string payload = new String('x', 1440);
            byte[] paybytes = Encoding.ASCII.GetBytes(payload);
            Socket send = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            try { send.Connect(remote); }
            catch (Exception e)
            {
                Console.WriteLine("Exception during socket connection/creation: {0}", e.ToString());
                throw;
            }

            Console.WriteLine("\"Connected\" to {0}", send.RemoteEndPoint.ToString());
            Console.WriteLine("Generating payload. Smoke meth and hail stan erryday.");
            Console.WriteLine("Brace for packets.");
            for (int i = 0; i < 666420; i++ )
            {
                try
                {
                    int bsent = send.Send(paybytes);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Unable to send packets. Balls. Error: {0}", e.ToString());
                    throw;
                }
            }
            Console.WriteLine("Shutting down the socket");
            Console.WriteLine("Today was a good day.");
            send.Shutdown(SocketShutdown.Both);
            send.Close();
        }
开发者ID:hazmats,项目名称:pslam,代码行数:35,代码来源:packets.cs

示例14: RunReciever

        public void RunReciever()
        {

            ListenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
            try
            {
                // Setup the Socket
                ListenSocket.Bind(new IPEndPoint(IPAddress.Parse(p_HostIP), 0));
                ListenSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, 1);
                ListenSocket.IOControl(unchecked((int) 0x98000001), new byte[4] {1, 0, 0, 0}, new byte[4]);
                while (true) //Infinite Loop keeps the Socket in Listen
                {
                    ListenSocket.BeginReceive(p_PacketBuffer, 0, p_PacketBufferSize, SocketFlags.None,
                                                new AsyncCallback(CallReceive), this); 

                    while (ListenSocket.Available == 0) // If no Data Sleep the thread for 1ms then check to see if there is data to be read
                    {
                        Thread.Sleep(1);
                    }
                }
            }
            catch (ThreadAbortException){}// Catch the ThreadAbort Exception that gets generated whenever a thread is closed with the Thread.Abort() method
            catch (Exception e) {new ErrorHandle(e);}
            finally //Shutdown the Socket when finished
            {
                if (ListenSocket != null)
                {
                    ListenSocket.Shutdown(SocketShutdown.Both);
                    ListenSocket.Close();
                }
            }
        }
开发者ID:d3xt3-bitstechlab,项目名称:PacketSniffer,代码行数:32,代码来源:Listen.cs

示例15: RefreshTorIdentity

 public void RefreshTorIdentity()
 {
     Socket server = null;
     try
     {
         IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9151);
         server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
         server.Connect(ip);
         // Please be sure that you have executed the part with the creation of an authentication hash, described in my article!
         server.Send(Encoding.ASCII.GetBytes("AUTHENTICATE \"johnsmith\"" + Environment.NewLine));
         byte[] data = new byte[1024];
         int receivedDataLength = server.Receive(data);
         string stringData = Encoding.ASCII.GetString(data, 0, receivedDataLength);
         server.Send(Encoding.ASCII.GetBytes("SIGNAL NEWNYM" + Environment.NewLine));
         data = new byte[1024];
         receivedDataLength = server.Receive(data);
         stringData = Encoding.ASCII.GetString(data, 0, receivedDataLength);
         if (!stringData.Contains("250"))
         {
             Console.WriteLine("Unable to signal new user to server.");
             server.Shutdown(SocketShutdown.Both);
             server.Close();
         }
     }
     finally
     {
         server.Close();
     }
 }
开发者ID:kennedykinyanjui,项目名称:Projects,代码行数:29,代码来源:TorTests.cs


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