c#save tcpclients连接到服务器

时间:2014-01-06 14:48:48

标签: c# networking tcpclient

我是c#的新手,我正在构建服务器/客户端应用程序。 我已经成功创建了服务器和客户端,但是当任何客户端连接到服务器时...我需要保存该客户端,因为服务器应该在10分钟后向他们发送消息。

private void Form1_Load(object sender, EventArgs e) {
    TcpListener myList;

    myList = new TcpListener(IPAddress.Any, 8001);

    while (true)

    {
        TcpClient client = myList.AcceptTcpClient();

        MessageBox.Show("Connection accepted from " + client.Client.LocalEndPoint.ToString());
    }
}

现在,我的问题是如何保存“客户端”ID或任何有关此连接的客户端的信息,以便在10分钟后从服务器发送到此客户端。

有人可以帮忙吗?

3 个答案:

答案 0 :(得分:2)

表格onLoad是接受客户的好地方。而是使用例如Background Worker。此外,您可能希望避免使用while(true)而无法打破循环。

对象存储必须在方法(事件处理程序)之外,以保护与邪恶垃圾收集器的连接。有许多方法可以存储对象,它可能是数组(麻烦)或某些集合,虽然计算较重但使用起来很愉快。您甚至可以使用Concurent集合,它们将自己处理线程同步。

Dictionary<string,TcpClient> clientDict;
List<TcpClient> clientList;
...
void acceptClients()
{

    TcpListener myList;

    myList = new TcpListener(IPAddress.Any, 8001);

    while (true)

    {
        TcpClient client = myList.AcceptTcpClient();
        clientDict.Add("client nickname, id etc.",client);
        clientList.Add(client);

        MessageBox.Show("Connection accepted from " + client.Client.LocalEndPoint.ToString());
        if (clientList.count>=8 || clientDict.count>=8)
        {
            break; // I want to break freeeeee!!!!
        }
    }
}
...
void sendToClient(string nick)
{
    if (clientDict.ContainsKey(nick))
    {
        TcpClient client = clientDict[nick];
        //and use selected client.
    }

}
void broadcast()
{
    foreach(TcpClient client in clientList) //clientList can be replaced with clientDict.Values
    {
        //and use selected client.
    }
}

答案 1 :(得分:1)

您必须将TCPClient存储在某个列表/字典中。关于识别连接,您可以使用TCPClient中的IP /端口来区分不同的连接。

以下是我发布的一篇文章,用于创建多线程TCP聊天应用程序。它可能会有所帮助。

http://shoaibsheikh.blogspot.com/2012/05/multi-threaded-tcp-socket-chat-server.html

答案 2 :(得分:1)

唯一可能的方法是保持连接打开。由于许多客户端从NAT设备后面连接(公司接入点,家庭路由器等),因此无法要求客户端进行回拨。地址(IP:端口)。

C#代码的含义是,您需要引用client中创建的AcceptTcpClient对象。当您想要发送内容时,您必须将此对象和Write内容检索到客户端的流中(通过client.GetStream()获得)。这究竟是如何完成的,完全取决于您的代码。也许是Dictionary 希望连接已经因各种原因而关闭,即使设置了KeepAlive也是如此。

请注意,拥有大量已接受的连接是不可行的(出于多种原因)。