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


C# NetworkStream.Close方法代码示例

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


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

示例1: Insert

        public override void Insert(Person person)
        {
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Connect(IPAddress.Parse("127.0.0.1"), 3180);

            NetworkStream networkStream = new NetworkStream(socket);

            string dataSend = extension + "|" + "Insert|" + person.ToXML();

            byte[] bytes = Encoding.UTF8.GetBytes(dataSend);
            networkStream.Write(bytes, 0, bytes.Length);

            bool isWork = true;
            while (isWork)
            {
                if (networkStream.DataAvailable)
                {
                    isWork = false;
                    byte[] buffer = new byte[socket.Available];
                    networkStream.Read(buffer, 0, buffer.Length);
                    string result = Encoding.UTF8.GetString(buffer);
                }
            }
            networkStream.Flush();
            networkStream.Close();
            socket.Close();
        }
开发者ID:tearose,项目名称:OurRepository,代码行数:27,代码来源:DataBaseNetClient.cs

示例2: EnviarDatos

 public void EnviarDatos(string mensaje)
 {
     clientStream = client.GetStream();
     data = System.Text.Encoding.ASCII.GetBytes(mensaje);
     clientStream.Write(data, 0, data.Length);
     clientStream.Close();
 }
开发者ID:Graid,项目名称:ChatProyectoFinDeCurso,代码行数:7,代码来源:ClienteTCP.cs

示例3: Service

 public static void Service()
 {
     while (true)
     {
         Socket soc = listener.AcceptSocket();
         try {
             Stream s = new NetworkStream(soc);
             StreamReader sr = new StreamReader(s);
             StreamWriter sw = new StreamWriter(s);
             sw.AutoFlush = true;
             sw.WriteLine("Send Message: ");
             while (true)
             {
                 string msg = sr.ReadLine();
                 if (msg == "" || msg == null) break;
                 Console.WriteLine(msg);
                 sw.WriteLine("Message received");
             }
             s.Close();
         }
         catch(Exception e){
             Console.WriteLine(e.Message);
         }
         soc.Close();
     }
 }
开发者ID:himach,项目名称:githubtest,代码行数:26,代码来源:SocServer.cs

示例4: DeleteData

 /// <summary>
 /// hungvv =======================Xoa ===========================
 /// </summary>
 private void DeleteData(string ID)
 {
     try
     {
         dh = new Entities.DonDatHang();
         cl = new Server_Client.Client();
         this.client = cl.Connect(Luu.IP, Luu.Ports);
         dh = new Entities.DonDatHang("Delete", ID);
         clientstrem = cl.SerializeObj(this.client, "DonDatHang", dh);
         int trave = 0;
         trave = System.Convert.ToInt32(cl.DeserializeHepper(clientstrem, trave));
         client.Close();
         clientstrem.Close();
         if (trave == 1)
         {
             SelectData();
             MessageBox.Show("Thành công !");
         }
         if (trave == 0)
         {
             MessageBox.Show("Thất bại !");
         }
     }
     catch (Exception)
     { }
 }
开发者ID:mrk29vn,项目名称:vna-accounting,代码行数:29,代码来源:frmHienThi_DonDatHang.cs

示例5: Comunica2

        public void Comunica2()
        {
            try
            {
                stream = client.GetStream();

                while (true)
                {

                    Byte[] byteStream = new byte[BUFFER_SIZE];

                    pegaTeclas();
                    write();
                    read(ref byteStream);

                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            finally
            {
                stream.Close();
                client.Close();
            }
        }
开发者ID:andresalerno88,项目名称:SuperTank,代码行数:27,代码来源:GerenciadorRede.cs

示例6: Main

        static void Main(string[] args)
        {
            Console.Write("포트번호입력(1024 - 65535): ");
            int port = int.Parse(Console.ReadLine());
            IPEndPoint myAddr = new IPEndPoint(IPAddress.Any, port);
            Socket server = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream,
                ProtocolType.Tcp);
            server.Bind(myAddr);

            server.Listen(10);
            Console.WriteLine("서버 시작");

            while (true)
            {
                Socket client = server.Accept();
                Console.WriteLine("클라이언트 {0} 접속",
                    client.RemoteEndPoint.ToString());
                NetworkStream ns = new NetworkStream(client);

                int len;
                string msg;
                while ((len = ns.Read(buf, 0, buf.Length)) != 0)
                {
                    msg = Encoding.UTF8.GetString(buf, 0, len);
                    Console.WriteLine("수신: {0}" , msg);
                    ns.Write(buf, 0, len);
                }
                Console.WriteLine("클라이언트 {0} 접속종료",
                    client.RemoteEndPoint.ToString());
                ns.Close();
                client.Close();
            }
        }
开发者ID:honux77,项目名称:prostar,代码行数:34,代码来源:Server.cs

示例7: DoIt

        public static void DoIt(Socket acceptedSocket, List<string> messages)
        {
            Socket connectionSocket = acceptedSocket;

            Console.WriteLine("Server activated");

            Stream ns = new NetworkStream(connectionSocket);
            StreamReader sr = new StreamReader(ns);
            StreamWriter sw = new StreamWriter(ns);
            sw.AutoFlush = true; // enable automatic flushing

            messages.Add(sr.ReadLine());
            while (!String.IsNullOrEmpty(messages[messages.Count - 1]))
            {
                Console.WriteLine("Client: " + messages[messages.Count - 1]);
                try
                {
                    sw.WriteLine(StringToString(messages));
                    messages.Add(sr.ReadLine());
                }
                catch (IOException ex)
                {
                    Console.WriteLine("Exception !");
                    break;
                }
            }
            ns.Close();
            connectionSocket.Close();
        }
开发者ID:BinAladin,项目名称:HTTPServer,代码行数:29,代码来源:Program.cs

示例8: backgroundWorker_DoWork

 void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
 {
     while (true)
       {
     Socket socketForClient = tcpListener.AcceptSocket();
     if (socketForClient.Connected)
     {
       Write("Client connected");
       NetworkStream networkStream = new NetworkStream(socketForClient);
       System.IO.StreamWriter streamWriter =
     new System.IO.StreamWriter(networkStream);
       System.IO.StreamReader streamReader =
     new System.IO.StreamReader(networkStream);
       string theString = "Sending";
       streamWriter.WriteLine(theString);
       Write(theString);
       streamWriter.Flush();
       theString = streamReader.ReadLine();
       Write(theString);
       streamReader.Close();
       networkStream.Close();
       streamWriter.Close();
     }
     else
     {
       Write("Exiting...");
       break;
     }
     socketForClient.Close();
       }
 }
开发者ID:andrewjswan,项目名称:youtube-fm-for-mediaportal,代码行数:31,代码来源:Server.cs

示例9: SendCmdRequest

        public bool SendCmdRequest(CmdRequest request)
        {
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                socket.Connect("127.0.0.1", Port);
                using (NetworkStream stream = new NetworkStream(socket))
                {
                    using (BsonWriter writer = new BsonWriter(stream))
                    {
                        JsonSerializer serializer = new JsonSerializer();
                        serializer.Serialize(writer, request);
                        writer.Flush();
                        writer.Close();
                    }
                   
                    stream.Close();
                }
            }
            catch(Exception ex)
            {
                Logger.AddError(string.Format("Failed to send cmd request to checker with port = {0}", Port), ex);
                return false;
            }

            return true;
        }
开发者ID:intech,项目名称:Checker,代码行数:28,代码来源:ThreadProcess.cs

示例10: RecieveFile

        public void RecieveFile(NetworkStream netStream)
        {
            byte[] data = new byte[1024];
            int dataCitit;
            int totalBytes = 0;

            FileStream fs = new FileStream("$temp", FileMode.Create, FileAccess.Write);

            do
            {
                dataCitit = netStream.Read(data, 0, data.Length);
                fs.Write(data, 0, dataCitit);
                totalBytes += dataCitit;

            } while (netStream.DataAvailable);

            fs.Close();
            netStream.Close();

            BinaryFormatter binFormatter = new BinaryFormatter();
            DataTable contentOfFile;
            byte[] outData;

            using (MemoryStream ms = new MemoryStream(File.ReadAllBytes("$temp")))
            {
                contentOfFile = (DataTable) binFormatter.Deserialize(ms);
                outData = (byte[]) contentOfFile.Rows[0].ItemArray.GetValue(2);
            }

            File.WriteAllBytes(contentOfFile.Rows[0].ItemArray.GetValue(0).ToString()+contentOfFile.Rows[0].ItemArray.GetValue(1), outData);
            File.Delete("$temp");
        }
开发者ID:YuraSidorets,项目名称:rep0,代码行数:32,代码来源:ClientTcpWorker.cs

示例11: RecieveFileDict

        /// <summary>
        /// Recieve Dictionary of (string, object) that contains all info about recieved file 
        /// </summary>
        /// <param name="reciever">Socket of transfer</param>
        private void RecieveFileDict(Socket reciever)
        {
            NetworkStream netStream = new NetworkStream(reciever);

            byte[] data = new byte[1024];
            int dataCitit;
            int totalBytes = 0;
            List<byte> listOfDict = new List<byte>();
            while ((dataCitit = netStream.Read(data, 0, data.Length)) > 0)
            {
                listOfDict.AddRange(data);
                totalBytes += dataCitit;
            }

            BinaryFormatter bf = new BinaryFormatter();
            using (MemoryStream ms = new MemoryStream(listOfDict.ToArray()))
            {
                this.contentOfAddingFile = (Dictionary<string, object>)bf.Deserialize(ms);
            }

            TestDisplay();

            DBWorker.SetValue(contentOfAddingFile);
            Console.WriteLine("Получено байт: {0}", totalBytes);
            netStream.Close();
        }
开发者ID:YuraSidorets,项目名称:rep0,代码行数:30,代码来源:TcpWorker.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: sendData

        public void sendData(String message)
        {
            try {

                clientSocket = new TcpClient();

                clientSocket.Connect(IPAddress.Parse("127.0.0.1"), 6000);
                if (clientSocket.Connected)
                {

                    stream = clientSocket.GetStream();

                    writer = new BinaryWriter(stream);
                    Byte[] tempMsg = Encoding.ASCII.GetBytes(message);

                    writer.Write(tempMsg);
                    Console.WriteLine("Data Sent- "+ message);
                    writer.Close();
                    stream.Close();

                }

            }
            catch (Exception e)
            {
                Console.WriteLine("Communication (WRITING) Failed! due to "+ e.Message);
                sendData(message);
            }
            finally
            {
                clientSocket.Close();

            }
        }
开发者ID:ChaminW,项目名称:TankGame,代码行数:34,代码来源:client.cs

示例14: connect_sync

        public NetworkStream connect_sync()
        {
            try
            {
                ConnectionStatistics.numberOfConnections++;
                //Establish a connection to the node
                channel = new TcpClient();
                channel.Connect(node.GetEndPoint());

                //Get a stream to the node
                stream = channel.GetStream();
                ConnectionStatistics.numberOfConnections++;

                if(stream == null)
                {
                    ConnectionStatistics.missedConnections++;
                    channel.Close();
                    return null;
                }

                if(!stream.CanRead || !stream.CanWrite)
                {
                    ConnectionStatistics.noReadWritePermissions++;
                    stream.Close();
                    channel.Close();
                    return null;
                }
            }
            catch
            {
                return null;
            }
            return stream;
        }
开发者ID:beghbali,项目名称:ResourceRingEntropyNetwork,代码行数:34,代码来源:Connection.cs

示例15: Start

        public void Start( CancellationToken token )
        {
            _newsock.Bind(_ipep);
            _newsock.Listen(10);

            Console.WriteLine("Waiting for a client...");

            var client = _newsock.Accept();
            var newclient = (IPEndPoint)client.RemoteEndPoint;

            Console.WriteLine("Connected with {0} at port {1}", newclient.Address, newclient.Port);

            using (var ns = new NetworkStream (client))
            {
                var mp = new TcpMultiplexer ();
                var capService = new CapService (mp);

                var rwStream = mp.CreateStream (CapName, TcpMultiplexer.Direction.InOut);

                var t1 = Task.Factory.StartNew (() => ReadAndAck (rwStream, CapName, token, capService));
                t1.Wait (token);

                Console.WriteLine ("Disconnected from {0}", newclient.Address);
                ns.Close ();
            }
        }
开发者ID:rudi77,项目名称:channelmultiplexer,代码行数:26,代码来源:Server.cs


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