代码到服务器:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace GatherServer
{
class Program
{
public static int connections = 0, team1 = 0, team2 = 0;
static TcpListener myList = new TcpListener(IPAddress.Any, 9874);
static void Listeners()
{
Socket socketForClient = myList.AcceptSocket();
if(socketForClient.Connected)
{
connections++;
Console.WriteLine("Client Connected: " + socketForClient.RemoteEndPoint);
NetworkStream networkStream = new NetworkStream(socketForClient);
StreamWriter streamWriter = new StreamWriter(networkStream);
StreamReader streamReader = new StreamReader(networkStream);
while (true)
{
string newString = streamReader.ReadLine();
if (newString == "exit")
{
Console.WriteLine("Player has left the game: "+socketForClient.RemoteEndPoint);
break;
}
else
{
streamWriter.WriteLine(connections.ToString());
streamWriter.Flush();
if (connections == 12)
{
Random rnd = new Random();
int team = rnd.Next(1, 3); // creates a number between 1 and 2
if(team == 1)
{
if (team1 < 6)
{
team1++;
Console.WriteLine("Player " + socketForClient.RemoteEndPoint + " assigned to Team 1");
streamWriter.WriteLine("team1");
streamWriter.Flush();
break;
}
else
{
Console.WriteLine("Player " + socketForClient.RemoteEndPoint + " assigned to Team 2");
team2++;
streamWriter.WriteLine("team2");
streamWriter.Flush();
break;
}
}
if(team == 2)
{
if (team2 < 6)
{
Console.WriteLine("Player " + socketForClient.RemoteEndPoint + " assigned to Team 2");
team2++;
streamWriter.WriteLine("team2");
streamWriter.Flush();
break;
}
else
{
Console.WriteLine("Player " + socketForClient.RemoteEndPoint + " assigned to Team 1");
team1++;
streamWriter.WriteLine("team1");
streamWriter.Flush();
break;
}
}
}
}
}
connections--;
streamWriter.Close();
streamReader.Close();
networkStream.Close();
socketForClient.Close();
}
}
static void Main(string[] args)
{
myList.Start();
Console.WriteLine("Sever is up and running...");
for(int i=0; i<100; i++)
{
Thread newThread = new Thread(new ThreadStart(Listeners));
newThread.Start();
}
}
}
}
我在路由器中打开了端口,我禁用了防火墙.. 帮助