如何創建多個客戶是代碼如何在一臺服務器上創建多個客戶端?
的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();
}
}
它不能正常工作。我想要第一個線程工作並結束,然後第二個線程開始。但是此代碼一次生成所有三種威脅。我的觀點是,多個客戶端將由此代碼創建,他們將等待。當第一個客戶端與服務器一起工作時,第二個客戶端將獲得服務器連接。
請擴大「在其不工作」。你看到什麼錯誤?什麼時候做什麼? – 2013-02-10 21:29:10
'lock(obje)'的含義是什麼? – 2013-02-10 21:30:39
沒有錯誤,但是當整個代碼一次運行所有的線程時。我想要一個線程一次訪問一個服務器。 @ImmortalBlue – Giliweed 2013-02-10 22:06:25