【问题标题】:TCP C# Packet to Specific ClientTCP C# 数据包到特定客户端
【发布时间】:2016-12-30 02:57:08
【问题描述】:

我正在编写一个 TCP 服务器来提高我对该协议的了解。最近,社区成员(René Vogt 先生)帮助我在我的服务器和多个客户端之间建立连接。

一切正常,答案(一个简单的活动数据包)正在发送给所有连接的客户端。但是现在,我想指定一个连接来发送数据包。我将做一个简短的解释:

服务器正在专用主机中运行。我的个人计算机作为 Client1 连接到服务器,发送一个活动数据包(“AA”)并接收服务器回复。然后,另一个客户端(Client2、client3... 等等)连接到服务器。将收到活着的消息,服务器将回复此客户端。但此外,我想向 Client1 发送一个像“Client2 is connected”(或其他任何东西)这样的数据包。

我的代码如下:

using System;
using System.Threading;
using System.Net.Sockets;
using MySql.Data.MySqlClient;
using System.Net;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            TcpListener serverSocket = new TcpListener(50000);
            TcpClient clientSocket = default(TcpClient);
            int counter = 0;

            serverSocket.Start();
            Console.WriteLine(" >> " + "Server Started");

        counter = 0;
            while (true)
            {
                counter += 1;
                clientSocket = serverSocket.AcceptTcpClient();
                Console.WriteLine(" >> " + "Client No:" + Convert.ToString(counter) + " started!");
                handleClinet client = new handleClinet();
                client.startClient(clientSocket, Convert.ToString(counter));
            }

            clientSocket.Close();
            serverSocket.Stop();
            Console.WriteLine(" >> " + "exit");
            Console.ReadLine();
        }
    }

    //Class to handle each client request separatly
    public class handleClinet
    {
        TcpClient clientSocket;

        string clNo;
        public void startClient(TcpClient inClientSocket, string clineNo)
        {
                this.clientSocket = inClientSocket;
                this.clNo = clineNo;
                Thread ctThread = new Thread(doChat);
                ctThread.Start();

        }
        private void doChat()
        {
            bool LoopReceive = true;
            bool LoopSend = false;
            int requestCount = 0;
            byte[] bytesFrom = new byte[256];
            string dataFromClient = null;
            Byte[] sendBytes = null;
            string serverResponse = null;
            string rCount = null;
            requestCount = 0;
            string Packettosend = "";

            while ((true))
            {
                try
                {
                    requestCount = requestCount + 1;
                    NetworkStream networkStream = clientSocket.GetStream();
                    networkStream.Flush();
                    networkStream.Read(bytesFrom, 0, bytesFrom.Length);
                    dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
                    IPEndPoint remoteIpEndPoint = clientSocket.Client.RemoteEndPoint as IPEndPoint;

                    Console.WriteLine(" >> PACKET: " + dataFromClient);



                    if (dataFromClient.StartsWith("AA")
                    {
                        Packettosend = "ALIVE";
                        Console.WriteLine("::ALIVE PACKET");
                    }


                    //PACKETS TO SEND
                    if (Packettosend == "ALIVE")
                    {
                        Byte[] sendBytes1 = { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 };
                        networkStream.Write(sendBytes1, 0, sendBytes1.Length);
                    }

                }
                catch (Exception ex)
                {
                    Console.WriteLine(" >> " + ex.ToString());
                }
            }
        }
    }
}

我搜索了一些答案,但没有奏效。除了当前发送数据包的客户端之外,是否可以将网络流指向其他任何东西?

提前致谢!

【问题讨论】:

  • 没有。不在同一个连接上。您的代码正在网络的数据层发送数据。您可以编写一个应用程序层来处理诸如“向 Client2 发送消息”、“列出当前连接”、“是否已连接 Clinet2”等命令。然后服务器将处理命令并发送回响应。
  • 但是怎么做呢?我是初学者,如果可能的话,一个简单的例子会很棒。
  • 代码不简单。最好的学习方式是阅读书籍以了解“网络通信”和“7 网络层”的基本原理。我在网上看到的大多数代码都不理解基本的通信理论,也没有正确地将代码分成适当的层。我拥有电气工程师的 BSEE、计算机科学的 MSCS、24 个博士学位和 40 年的工作经验。我可以写书并教授课程。但不举个简单的例子。
  • 没有其他人吗? :(

标签: c# sockets networking tcp


【解决方案1】:

简单的代码是,将客户端存储到带有 id 或字典的客户端列表中,

Dictionary<TcpClient, int> clintlist= new Dictionary<TcpClient, int>();

当你想 发送特定客户端只需搜索客户端列表中的 id

【讨论】: