如果客户端关闭,请重新连接

时间:2018-09-06 12:06:42

标签: c# sockets

我有一个带有套接字的程序可以聊天。如果从客户端端连接时关闭,则此程序会出现问题。我正在寻找服务器自动 等待程序重新连接的方式。

此代码套接字等待

    private async void OnWindowLoaded(object sender, EventArgs e)
    {
        await Task.Run(() => {
            Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint serv = new IPEndPoint(IPAddress.Parse(Properties.Settings.Default.IP),
                Properties.Settings.Default.Port);
            sock.Bind(serv);
                while (true)
                {
                    sock.Listen(5);
                    cli = sock.Accept();
                }
        });
    }

此代码收到

    private Task<string> DoWork()
    {
        return Task.Run(() =>
        {
            try
            {
                byte[] datass = new byte[1024];
                rec = cli.Receive(datass);
                recc = Environment.NewLine + (Encoding.ASCII.GetString(datass, 0, rec));
            }
            catch (Exception)
            {
                timer2.Enabled = false;
                recc = null;
            }
            return recc;
        });
    }

0 个答案:

没有答案