gpt4 book ai didi

C# tcp 套接字定义客户端

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

我正在尝试使用 Visual Studio 2010 设置一个 tcp .net 套接字网络。到目前为止它可以工作,我可以将客户端连接到它,但目前我无法定义连接的客户端。我需要一组已连接的客户端,这样我就可以更具体地说明我要流式传输给谁。

这是我的服务器代码,我正在从 http://www.codeproject.com/Articles/511814/Multi-client-per-one-server-socket-programming-in 复制所有这些代码

服务器代码

static TcpListener tcpListener = new TcpListener(25000);

static void Listeners()
{
Socket socketForClient = tcpListener.AcceptSocket();
if (socketForClient.Connected)
{
Console.WriteLine("Client:"+socketForClient.RemoteEndPoint+" now connected to server.");
NetworkStream networkStream = new NetworkStream(socketForClient);

System.IO.StreamWriter streamWriter =
new System.IO.StreamWriter(networkStream);
System.IO.StreamReader streamReader =
new System.IO.StreamReader(networkStream);


Console.WriteLine("type your message to be recieved by client:");
string theString2 = Console.ReadLine();
streamWriter.WriteLine(theString2);
Console.WriteLine(theString2);
streamWriter.Flush();

while (true)
{
string theString = streamReader.ReadLine();
Console.WriteLine("Message recieved by client:" + theString);
if (theString == "exit")
break;
}
streamReader.Close();
networkStream.Close();
streamWriter.Close();


}
socketForClient.Close();
Console.WriteLine("Press any key to exit from server program");
Console.ReadKey();
}

public static void Main()
{
tcpListener.Start();
Console.WriteLine("************This is Server program************");
Console.WriteLine("Hoe many clients are going to connect to this server?:");
int numberOfClientsYouNeedToConnect = int.Parse(Console.ReadLine());
for (int i = 0; i < numberOfClientsYouNeedToConnect; i++)
{
Thread newThread = new Thread(new ThreadStart(Listeners));
newThread.Start();
}
}

最佳答案

如果你想坚持使用原始 TCP 套接字,那么你可以将委托(delegate)/处理程序等传递给线程:

for (int i = 0; i < numberOfClientsYouNeedToConnect; i++)
{
Thread newThread = new Thread(new ParameterizedThreadStart(Listeners));
newThread.Start(i);
}

然后您的监听器需要采用一个对象 来匹配ParametrizedThreadStart see MSDN

但是,如果您正在开发两端(正如我评论的那样),我会建议一些更抽象的东西,例如 ASP.NET SignalR或类似的情况。它增加了一些开销,但您可以在方便的抽象级别上获得服务器到客户端的通信,反之亦然。

关于C# tcp 套接字定义客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31111529/

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