如何在C#中停止并开始重新启动客户端套接字连接

时间:2018-05-08 05:18:39

标签: c# sockets tcp-ip

我正在研究ATM项目(tcp / ip,C#)。我必须单击服务器应用程序中的开始按钮才能开始侦听客户端。 OInce客户端根据请求发送签名(连接),建立服务器和客户端之间的连接(直到本部分我已完成)。

当请求的签名来自客户端时,我必须断开连接并再次开始侦听客户端。监听客户端的代码如下。

public bool startlisten() 
{
        byte[] buffer = new byte[4000];

        try
        {
            //Creates one SocketPermission object for access restrictions
            permission = new SocketPermission(
                 NetworkAccess.Accept,     // Allowed to accept connections 
                 TransportType.Tcp,        // Defines transport types 
                 "",                       // The IP addresses of local host 
                 SocketPermission.AllPorts // Specifies all ports 
            );

            // Listening Socket object 
            sListener = null;

            //Ensures the code to have permission to access a Socket 
            permission.Demand();

            // Resolves a host name to an IPHostEntry instance 
            IPHostEntry ipHost = Dns.GetHostEntry("");

            int portnumber = int.Parse(ConfigurationManager.AppSettings.Get("port"));

            // Creates a network endpoint 
            ipEndPoint = new IPEndPoint(IPAddress.Any, portnumber);

            // Create one Socket object to listen the incoming connection 
            sListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // Associates a Socket with a local endpoint 
            sListener.Bind(ipEndPoint);


            // Places a Socket in a listening state and specifies the maximum 
            // Length of the pending connections queue 
            sListener.Listen(10);

            //Begins an asynchronous operation to accept an attempt 
            AsyncCallback aCallback = new AsyncCallback(AcceptCallback);
            sListener.BeginAccept(aCallback, sListener);


        }
        catch (Exception exc) {
            return true;
        }

        return true;
}

请指导我如何从客户端套接字断开连接并再次开始收听。

我试过了

//handler.Disconnect(false);                
           //handler.Shutdown(SocketShutdown.Both);
           //handler.Close();

sListener和handler是Socket对象。接受(acceptconnection)侦听器被复制到handler。

0 个答案:

没有答案