-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServer.cs
More file actions
94 lines (75 loc) · 2.6 KB
/
Server.cs
File metadata and controls
94 lines (75 loc) · 2.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
namespace Network
{
static class Server
{
public static int port = 6969;
public static IPAddress ip = IPAddress.Any;
public static int maxPlayers = 32;
public static TcpListener tcpListener = new TcpListener(ip, port);
public static List<Client> clients = new List<Client>();
public static void Start(int playerLimit = 32)
{
if (IsRunning())
Stop();
maxPlayers = playerLimit;
tcpListener.Start();
tcpListener.Beg
Console.WriteLine("Server started on ip = " + ip + " port = " + port);
}
private static void TcpConnectCallback(IAsyncResult result)
{
Client client = new Client(tcpListener.EndAcceptTcpClient(result));
AddClient(client);
tcpListener.BeginAcceptTcpClient(new AsyncCallback(TcpConnectCallback), null);
}
private static void AddClient(Client client)
{
if (clients.Count >= maxPlayers)
{
Server.NotifyAll("Server full!");
return;
}
clients.Add(client);
if (clients.Count == 1)
client.admin = true;
Server.NotifyAll(client.name + " joined the server!");
}
public static void Notify(Client client, string message)
{
NetworkPacket packet = new NetworkPacket("print");
packet.WriteString(message);
packet.SendToClient(client);
}
public static void NotifyAll(string message)
{
NetworkPacket packet = new NetworkPacket("print");
packet.WriteString(message);
packet.SendToClients();
}
public static void Stop()
{
NotifyAll("Server closing");
foreach (Client client in clients)
if (client.IsConnected())
client.Disconnect();
tcpListener.Server.Close();
tcpListener.Stop();
}
public static Client GetClient(string name)
{
foreach (Client client in clients)
if (client.name == name && client.IsConnected())
return client;
return null;
}
public static bool IsRunning()
{
return tcpListener.Server.Connected;
}
}
}