如何使用 is 代码创建多个客户端
程序.cs
class Program
{
static void Main(string[] args)
{
Server.ServerCode(5656);
}
}
客户端.cs
class Client
{
public static void ClientCode()
{
//SOCKET CONNECTION
//int Port = (int)port;
Console.WriteLine("......................CLIENT.........................");
TcpClient client = new TcpClient("127.0.01", 5656);
NetworkStream clientStream = client.GetStream();
StreamReader sr = new StreamReader(clientStream);
StreamWriter sw = new StreamWriter(clientStream);
sw.AutoFlush = true;
//CLOSING SOCKET
clientStream.Close();
client.Close();
Console.ReadLine();
}
}
我的服务器代码:
服务端.cs
class Server
{
public static void ServerCode(object port)
{
//SOCKET CONNECTION
int Port = (int)port;
Console.WriteLine("................SERVER RUNNING......................");
TcpListener listener = new TcpListener(IPAddress.Parse("127.0.0.1"), Port);
listener.Start();
while (true)
{
TcpClient serverSite = listener.AcceptTcpClient();
if (serverSite.Connected)
{
Thread c = new Thread((fileTransfer));
c.Start(serverSite);
}
}
}
public static void fileTransfer(object clients)
{
Console.WriteLine("new client");*/
TcpClient server = listener.AcceptTcpClient();//(TcpClient)clients;
NetworkStream serverStream = server.GetStream();
StreamReader sr = new StreamReader(serverStream);
StreamWriter sw = new StreamWriter(serverStream);
sw.AutoFlush = true;
//CHECKING USERNAME AND PASSWORD
Console.WriteLine("Connecting to Client... ");
string fromClient_u = sr.ReadLine();
Console.WriteLine("\n Username: " + fromClient_u);
string fromClient_p = sr.ReadLine();
Console.WriteLine("\n Password: *******");
if (fromClient_u == "Client1" && fromClient_p == "123456")
{
Console.WriteLine("\nClient has Successfully Loged In. ");
sw.WriteLine("Connection Complete... "); //msg1
sw.WriteLine("Successfully Connected to the Server."); //msg2
sw.WriteLine("Enter Some Informations for File Transfer..."); //msg3
}
//CLOSING SOCKET
serverStream.Close();
server.Close();
Console.ReadLine();
}
}
它不工作。我希望第一个线程工作并结束,然后第二个线程开始。但是此代码会同时生成所有三个威胁。我的意思是,此代码将创建多个客户端,他们将等待。当第一个客户端完成与服务器的工作时,第二个客户端将获得服务器连接。