C# 断开服务器出口上的客户端

C# 断开服务器出口上的客户端,c#,signalr,C#,Signalr,以下是我正在使用的服务器代码: using System; using Microsoft.AspNet.SignalR; using Microsoft.AspNet.SignalR.Hubs; using Microsoft.Owin.Hosting; using Owin; using Microsoft.Owin.Cors; using System.Collections.Generic; namespace flar3server { class Program

以下是我正在使用的服务器代码:

using System;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using Microsoft.Owin.Hosting;
using Owin;
using Microsoft.Owin.Cors;
using System.Collections.Generic;


namespace flar3server
{
    class Program
    {
        static void Main(string[] args)
        {
            string url = "http://localhost:8080/";
            using (WebApp.Start(url))
            {
                Console.WriteLine("Server running on {0}", url);
                Console.ReadLine();
            }
        }

        [HubName("flar3hub")]
        public class flare3hub : Hub
        {
            static Dictionary<string, ChatConnection> connections = new Dictionary<string, ChatConnection>();
            Dictionary<string, string> registeredUsers = new Dictionary<string, string>()
            {
                { "test1", "pass1" },
                { "test2", "pass2" },
            };

            /*
            public string Send(string message)
            {
                return message;
            }
             */

            public void Authenticate(string login, string password)
            {
                Console.WriteLine("Login [" + Context.ConnectionId + "] " + login + ":" + password);
                foreach (ChatConnection connection in connections.Values)
                {
                    if (connection.getLogin() == login)
                    {
                        Clients.Caller.Action("ERROR: User already logged in.");
                        return;
                    }
                }
                if (!registeredUsers.ContainsKey(login) || registeredUsers[login] != password)
                {
                    Clients.Caller.Action("ERROR: Login attempt failed.");
                    return;
                }
                connections[Context.ConnectionId] = new ChatConnection(login);
                Clients.Caller.Action("Logged in successfully");
                Clients.All.Action(login + " joined the channel.");

            }

            public void Broadcast(string message)
            {
                try
                {
                    Clients.All.sendMessage(connections[Context.ConnectionId].getLogin(), message);
                }
                catch (KeyNotFoundException)
                {
                    Console.WriteLine("Unpaired [" + Context.ConnectionId + "] " + message);
                }
            }
        }
    }
}

使用系统;
使用Microsoft.AspNet.signal;
使用Microsoft.AspNet.signal.Hubs;
使用Microsoft.Owin.Hosting;
使用Owin;
使用Microsoft.Owin.Cors;
使用System.Collections.Generic;
命名空间flar3server
{
班级计划
{
静态void Main(字符串[]参数)
{
字符串url=”http://localhost:8080/";
使用(WebApp.Start(url))
{
WriteLine(“在{0}上运行的服务器”,url);
Console.ReadLine();
}
}
[HubName(“flar3hub”)]
公共类flare3hub:Hub
{
静态字典连接=新建字典();
Dictionary registeredUsers=新字典()
{
{“test1”,“pass1”},
{“test2”,“pass2”},
};
/*
公共字符串发送(字符串消息)
{
返回消息;
}
*/
公共无效身份验证(字符串登录、字符串密码)
{
Console.WriteLine(“Login[”+Context.ConnectionId+“]””]“+Login+”:“+密码);
foreach(连接中的ChatConnection.Values)
{
if(connection.getLogin()==login)
{
Clients.Caller.Action(“错误:用户已登录。”);
返回;
}
}
if(!registeredUsers.ContainsKey(登录)| | registeredUsers[login]!=密码)
{
Clients.Caller.Action(“错误:登录尝试失败”);
返回;
}
connections[Context.ConnectionId]=新的聊天连接(登录);
Clients.Caller.Action(“成功登录”);
Clients.All.Action(登录+“加入频道”);
}
公共无效广播(字符串消息)
{
尝试
{
Clients.All.sendMessage(连接[Context.ConnectionId].getLogin(),message);
}
catch(KeyNotFoundException)
{
Console.WriteLine(“未配对[”+Context.ConnectionId+“]”+消息);
}
}
}
}
}
以下是客户端代码:

using System;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using Microsoft.AspNet.SignalR.Client;

namespace flar3client_cli
{
    internal class flar3client_cli
    {
        private static void onDisconnected()
        {
            Console.WriteLine("Remote server closed the connection. Press enter to close the application.");
            Console.ReadLine();
            System.Environment.Exit(1);
        }

        private static void Main(string[] args)
        {
            //Set connection
            var connection = new HubConnection("http://localhost:8080/");
            //Make proxy to hub based on hub name on server
            var myHub = connection.CreateHubProxy("flar3hub");
            //Start connection

            connection.Start().ContinueWith(task =>
            {
                if (task.IsFaulted)
                {
                    Console.WriteLine("There was an error opening the connection:{0}",
                                      task.Exception.GetBaseException());
                    Console.WriteLine("Press enter to continue...");
                    Console.ReadLine();
                    connection.Stop();
                    System.Environment.Exit(1);
                }
                else
                {
                    Console.WriteLine("Connected");
                }

            }).Wait();
            connection.Closed += onDisconnected;


            myHub.On<string>("Action", param =>
            {
                Console.WriteLine(param);
            });

            myHub.On<string>("SendMessage", param =>
            {
                Console.WriteLine(param);
            });

            myHub.Invoke<string>("Authenticate", "test1", "pass1").Wait();


            while (true)
            {
                myHub.Invoke<string>("Broadcast", Console.ReadLine()).Wait();
            }
使用系统;
使用Microsoft.AspNet.signal;
使用Microsoft.AspNet.signal.Hubs;
使用Microsoft.AspNet.signal.Client;
命名空间flar3client\u cli
{
内部类flar3client\u cli
{
私有静态无效onDisconnected()
{
WriteLine(“远程服务器关闭了连接。按enter键关闭应用程序”);
Console.ReadLine();
系统、环境、出口(1);
}
私有静态void Main(字符串[]args)
{
//设置连接
var连接=新的HUB连接(“http://localhost:8080/");
//基于服务器上的集线器名称创建到集线器的代理
var myHub=connection.createhubbroxy(“flar3hub”);
//启动连接
connection.Start().ContinueWith(任务=>
{
if(task.IsFaulted)
{
WriteLine(“打开连接时出错:{0}”,
task.Exception.GetBaseException());
Console.WriteLine(“按enter键继续…”);
Console.ReadLine();
连接。停止();
系统、环境、出口(1);
}
其他的
{
控制台。写入线(“连接”);
}
}).Wait();
连接。关闭+=断开连接;
myHub.On(“操作”,参数=>
{
控制台写入线(参数);
});
myHub.On(“SendMessage”,参数=>
{
控制台写入线(参数);
});
调用(“Authenticate”、“test1”、“pass1”).Wait();
while(true)
{
调用(“广播”,Console.ReadLine()).Wait();
}

如何使服务器在其应用程序窗口关闭时断开所有客户机的连接,以便客户机能够找到答案?

首先,我禁用了winform的x按钮。然后,我在winform上添加了一个启动按钮来启动signalr服务器。我还添加了一个停止按钮,当单击此停止按钮时,我调用clients.all.somef函数告诉所有客户端服务器将要关闭,这个过程可能需要几秒钟,我在服务器中启动一个计时器,比如说10秒钟,10秒钟后,我关闭winform!我就是这样做的

但事实上,我不知道如何使用控制台服务器。当服务器的应用程序窗口关闭时,我如何使服务器断开所有客户端的连接,以便客户端可以找到它

使用您的代码,客户端将发现服务器已离开,但只有在断开连接超时之后,客户端才会尝试重新建立连接,直到放弃为止。
如果需要,您可以这样做,但最好是将“嘿,服务器正在停机”消息发送到所有客户端…

您可以在服务器端使用winform而不是控制台吗?最坏的情况下我可以。您有解决方案吗?