网络-如何制作服务器? [英] Networking - How make a server?
问题描述
您好,我正在学习编程,因此我需要解决新问题.我想将服务器写入我的应用程序.我的问题在哪里?因此,当我的服务器从任何客户端接收消息时,它都应将重播发送给所有客户端.我不知道我的客户应该如何等待此重播,服务器中的所有三元组如何将相同的重播发送给客户端.
我的英语很抱歉:)
为了更好地了解我的问题,我制作了动画:
单击
Hi, I''m learning programming and I need help with my new problem. I want to write a server to my app. Where is my problem? So, when my server recives message from anyone client, it should sends replay to all clients. I don''t know how my clients should waiting for this replay and how all threeds in server send same replay to clients.
Sory for my English :)
To better see my problem I do animation:
click
推荐答案
每个客户端使用单独的线程是一种非常糟糕的主意.我不会带你去的为什么?
请查看我过去对相关问题的回答,它可以给您一个正确的主意:
来自同一端口号的多个客户端 [
Using a separate thread per client is a very bad idea. I will lead you nowhere. Why?
Please see my past answer to a related question, it can give you a right idea:
Multple clients from same port Number[^].
—SA
我做了类似的事情
I make samething like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
namespace server
{
class server
{
List<tcpclient> clientList;
TcpListener listener;
public server(int port)
{
clientList = new List<tcpclient>();
listener = new TcpListener(System.Net.IPAddress.Any, port);
listener.Start();
}
public void listengForClient()
{
Thread newClient = new Thread(listeningForNewClient);
newClient.Start();
}
private void listeningForNewClient()
{
while (true)
{
TcpClient client = default(TcpClient);
client = listener.AcceptTcpClient();
lock (clientList)
{
clientList.Add(client);
Console.WriteLine(" >> Adding new client... Client count: " + clientList.Count);
}
}
}
public void receiveDateFromClients()
{
Thread receiver = new Thread(receiveDate);
reciver.Start();
}
private void receiveDate()
{
while (true)
{
lock(clientList)
for (int i = 0; i < clientList.Count; i++)
{
if (clientList[i].Connected)
{
if (clientList[i].Available > 0)
{
// get message form i-client
Console.WriteLine(" >> >> >> Message from client: " + i);
}
}
else
{
// client disconnected so it is removing
Console.WriteLine(" >> >> Removing client: " + i);
clientList.RemoveAt(i);
i--; if (i < 0) i = 0;
}
}
}
}
}
}
</tcpclient></tcpclient>
我知道接收日期不好,因为它使用了95%的CPU,但是我不知道如何做得更好...
I know receiving date is bad, becaouse it uses 95% CPU, but I don''t know how do it better...
这篇关于网络-如何制作服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!