gpt4 book ai didi

c# - 到特定客户端的 TCP C# 数据包

转载 作者:可可西里 更新时间:2023-11-01 02:50:48 25 4
gpt4 key购买 nike

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

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

服务器在专用主机中运行。我的个人计算机作为 Client1 连接到服务器,发送一个事件数据包(“AA”)并接收服务器回复。然后,另一个客户端(Client2、client3...等等)连接到服务器。 alive 将被接收并且服务器将回答这个客户端。但除此之外,我想向 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

关于c# - 到特定客户端的 TCP C# 数据包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41390033/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com