如何使用代码
创建多个客户端Program.cs的
class Program
{
static void Main(string[] args)
{
Server.ServerCode(5656);
}
}
Client.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();
}
}
我的服务器代码:
sereve.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();
}
}
它不起作用。我希望第一个线程工作并结束,然后第二个线程开始。但是这段代码会同时生成所有三个威胁。我的观点是,这个代码将创建多个客户端,他们将等待。当第一个客户端完成与服务器一起工作时,第二个客户端将获得服务器连接。
答案 0 :(得分:2)
如果不提供服务器代码,也很难知道问题是否也存在。如果有一个比较结帐有助于本文介绍如何create a quick client and server application。该示例还允许任意数量的客户端,但它们必须作为独立进程启动,而不是线程。
要一次只运行一个客户端,您可以尝试更改起始代码,如下所示:
for (i = 0; i < 3; i++)
{
t[i].Start();
t[i].Join();
}
答案 1 :(得分:1)
听起来很简单,如果你想锁定进程直到客户端结束然后启动下一个进程,只需循环并明确调用它:
for (i=0;i<3;i++)
{
Client.ClientCode();
}