我正在编写TCP服务器以提高我对此协议的了解。最近,一个社区成员(RenéVogt先生)帮助我建立了我的服务器和多个客户端之间的连接。
一切正常,答案(简单的活动数据包)将被发送给所有连接的客户端。但现在,我想指定一个发送数据包的连接。我将简要解释一下:
服务器在专用主机中运行。我的个人计算机作为Client1连接到服务器,发送活动数据包(“AA”)并接收服务器回复。然后,另一个客户端(Client2,client3 ......和on)连接到服务器。将收到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());
}
}
}
}
}
我搜索了一些答案,但它们没有用。是否可以将网络流指向除发送数据包的当前客户端以外的任何其他内容?
提前致谢!
答案 0 :(得分:1)
简单的代码是,将客户端存储到具有id或字典的客户端列表
Dictionary<TcpClient, int> clintlist= new Dictionary<TcpClient, int>();
当你想要的时候 发送特定客户端只搜索客户列表中的ID