简体   繁体   中英

disconnecting a client from server after receiving message in c# socket

I have made a small client program which will receive a message from server. I want to disconnect the client from the server safely after receiving the message.(Another case may also arise such that, I want to compare the received value with another value and if the don't match, the client will be disconnected) My sample code is:

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text;
class Program
{

    static void Main(string[] args)
    {
        try
        {                
            TcpClient tcpClient = new TcpClient("127.0.0.1", 1234);

            NetworkStream ns = tcpClient.GetStream();
            StreamReader sr = new StreamReader(ns);
            StreamWriter sw = new StreamWriter(ns);
            string data;

            //receiving message
            data = sr.ReadLine();
            Console.WriteLine(data);

            //I want to disconnect here     
         }
        catch (Exception e)
        {
            Console.Write(e.Message);
        }

        Console.Read();
    }
}

What additional things will I need to add?

Just wrap the usage of the TcpClient instance and NetworkStream in a using block:

using(TcpClient tcpClient = new TcpClient("127.0.0.1", 1234))
using(NetworkStream ns = tcpClient.GetStream())
{
  // Do read here
}

I would structure your code more like:

using (var tcpClient = new TcpClient("127.0.0.1", 1234))
{
    using(var ns = tcpClient.GetStream())
    {
        StreamReader sr = new StreamReader(ns);
        StreamWriter sw = new StreamWriter(ns);
        string data;

        //receiving message
        data = sr.ReadLine();

        if(data == somePreDeterminedValue)
        {
            Console.WriteLine(data);
        }
    }
}

This will mean that when you hit the closing brace it'll automatically close the TCPClient and NetworkStream for you and dispose of their instances.

In this case if the value you get from the stream is correct then it won't disconnect, simple. I think you'll need to provide what you want to do overall for a complete answer to your question as in this simple terms that is what I'd do, but in this example the TCPClient is closed regardless.

In a real world application you'd essentially want to keep a field of the TCPClient that you open and close throughout the application and only dispose of when your messaging object is disposed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM