我正在研究用 C# 编写的多线程服务器和客户端。所以请指导我如何在服务器中为多客户端创建多线程。
这是我的服务器代码
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();
}
}