我正在研究用C#.So Guide编写的多线程服务器和客户端 我如何在服务器中为多客户端创建多线程。
这是我的服务器代码
class Program
{
static byte[] Buffer
{
get;
set;
}
static void Main(string[] args)
{
Program obj = new Program();
Console.WriteLine("Server");
obj.server_reciver();
}
static Socket sck;
public void server_reciver()
{
try
{
sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint localEndPoint;
localEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.2"), 1);
sck.Bind(localEndPoint);
sck.Listen(100);
while (true)
{
Socket accepted = sck.Accept();
// Buffer = new byte[accepted.ReceiveBufferSize];
Buffer = new byte[accepted.SendBufferSize];
int bytesRead = accepted.Receive(Buffer);
byte[] formatted = new byte[bytesRead];
//for (int i = 0; i < bytesRead; i++)
for (int i = 0; i < bytesRead; i++)
{
formatted[i] = Buffer[i];
//Console.WriteLine(Buffer[i] + "\r\n");
}
//string strData = Encoding.ASCII.GetString(Buffer);
string strData = Encoding.ASCII.GetString(formatted);
Console.Write("From Client=>" + strData + "\n");
Console.WriteLine("Enter the text:");
string data = Console.ReadLine();
byte[] reply = Encoding.ASCII.GetBytes(data);
accepted.Send(reply);
//accepted.Close();
accepted.Close();
}
sck.Close();
Console.Read();
}
catch (Exception ex)
{
}
}
}
这是我的客户端,我在这里制作了多个客户端
class Program
{
static byte[] Buffer
{
get;
set;
}
static Socket sck;
static void Main(string[] args)
{
Program obj = new Program();
obj.client_send();
}
public void client_send()
{
while (true)
{
sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint localEndPoint;
localEndPoint = new IPEndPoint(IPAddress.Parse("182.188.247.244"), 1);
//localEndPoint = new IPEndPoint(IPAddress.Parse("192.168.1.45"), 1);
try
{
sck.Connect(localEndPoint);
}
catch
{
Console.Write("Unable to connect to remote end point!\r\n");
//Main(args);
}
try
{
Console.Write("Enter Text: ");
string text = Console.ReadLine();
byte[] data = Encoding.ASCII.GetBytes(text);
sck.Send(data);
Buffer = new byte[sck.SendBufferSize];
int bytesRead = sck.Receive(Buffer);
byte[] formatted = new byte[bytesRead];
for (int i = 0; i < bytesRead; i++)
{
formatted[i] = Buffer[i];
//Console.WriteLine(Buffer[i] + "\r\n");
}
string strData = Encoding.ASCII.GetString(formatted);
Console.Write("From Server=>" + strData + "\n");
sck.Close();
}
catch(Exception )
{
}
}
Console.ReadLine();
}
}
答案 0 :(得分:0)
通常,您会在主线程上保留Socket accepted = sck.Accept();
,但是一旦收到请求,您就会将其传递给另一个线程进行维护。这允许主线程列出到另一个传入请求。您可以使用ThreadPool.QueueUserWorkItem
将工作移至后台线程。请注意,由于从控制台读取响应,因此将其设置为多线程会给您带来问题。每个工作线程如何知道它获得了正确的数据?但我认为你会用真正的服务器逻辑取代它。
在某些时候,您可能会发现这不会扩展。您正在使用阻止IO调用(Send
和Receive
),因此您的线程将花费大量时间等待。非阻塞IO是理想的,但编写起来更复杂。