将TCP C#数据包发送到特定客户端
问题描述:
我正在编写TCP服务器以提高我对此协议的了解。最近,一位社区成员(RenéVogt先生)帮助我建立了我的服务器和多个客户端之间的连接。将TCP C#数据包发送到特定客户端
一切正常,答案(一个简单的活动数据包)正在发送到所有连接的客户端。但是现在,我想指定一个连接来发送数据包。我将给出一个简短的解释:
服务器运行在专用主机上。我的个人计算机以Client1的身份连接到服务器,发送活动数据包(“AA”)并接收服务器回复。然后,另一个客户端(Client2,client3 ...和on)连接到服务器。活着将被收到,服务器将回答这个客户端。但是,另外,我希望向Client1发送一个类似“Client2已连接”(或其他任何内容)的数据包。
我的代码如下:
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());
}
}
}
}
}
我寻找一些答案,但他们没有工作。是否有可能将网络流指向发送数据包的当前客户端以外的其他任何东西?
在此先感谢!
答
简单的准则是,存储客户端与ID或字典的客户名单,
Dictionary<TcpClient, int> clintlist= new Dictionary<TcpClient, int>();
,当你想 发送特定的客户端只搜索ID上不上客户端列表
号相同的连接。您的代码正在网络的数据层发送数据。您可以编写一个应用程序层来处理命令,如“将消息发送到客户端2”,“列出当前连接”,“是否连接到Clinet2”。服务器然后会处理命令并发送回应。 – jdweng
但是如何?我是一个初学者,如果可能的话,一个简单的例子会很棒。 –
代码并不简单。最好的学习方法是阅读书籍以了解“网络通信”和“7网络层”的基本原理。我在网上发布的大部分代码都不了解基本的通信原理,也没有将代码正确地分离到适当的层中。我拥有电气工程师学士学位,计算机科学硕士学位,博士学位24学分,以及40年工作经验。我可以写这本书并教授课程。但不能举一个简单的例子。 – jdweng