using System;
using System.Data;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.ServiceProcess;
using System.Threading;
namespace TCBChatServer
{
public class ChatEngine
{
private ArrayList clients = new ArrayList(); // a list of all connected clients
internal TcpListener server; // the server
public ChatEngine(int port)
{
StartChatServer(port);
}
// Starts the server and listens for connections
// port is the Port number the server should listen to for connections.
private void StartChatServer(int port)
{
LogActivity("Attempting to Start Server");
try
{
foreach(IPAddress d in Dns.Resolve(Dns.GetHostName()).AddressList)
{
Console.WriteLine("SERVER IP: " + d.ToString());
}
// create a new server
IPAddress serverip = Dns.GetHostByName(Dns.GetHostName()).AddressList[1];
TcpListener temp_tcplistener = new TcpListener(serverip, port);
temp_tcplistener.Start();
server = temp_tcplistener;
LogActivity("Server Started on Port: " + port);
while (true)
{
// listen for new client connections
TcpClient socket = server.AcceptTcpClient();
ChatClient client = new ChatClient(this, socket);
LogActivity(client.Username + " connected to the server.");
// add the new client to our client list
clients.Add(client);
// start the client thread
client.Start();
}
}
catch
{
LogActivity("Server Error ... Stopping Server");
// kill this server
KillServer();
}
}
// broadcasts a message to all connected clients
public virtual void SendAllUsersMessage(System.String message)
{
lock(this)
{
// add the null character to the message
message += '\x0000';
foreach(ChatClient c in clients)
{
try
{
c.SendUserMessage(message);
}
catch
{
Disconnect(c);
}
}
}
}
public virtual void Disconnect(ChatClient client)
{
string username = client.Username;
LogActivity(username + " has left the server.");
clients.Remove(client);
SendAllUsersMessage("" + username + " left.");
SendClientCount();
}
public virtual void SendClientCount()
{
Console.WriteLine("sendclientcount: " + clients.Count);
SendAllUsersMessage("" + clients.Count + "");
}
// prints out a record of 'activity'
public virtual void LogActivity(String activity)
{
Console.Out.Write("[" + DateTime.Now.ToString("dd:MM:yyyy hh:mm:ss") + "] " + activity + "\n");
}
// stops the server
private void KillServer()
{
try
{
// stop the server
server.Stop();
LogActivity("Server Stopped");
}
catch
{
LogActivity("Error while stopping Server");
}
}
// initialiser. it's run using ChatEngine.exe 8080 where 8080 is the port
public static void Main(String[] args)
{
int port = 0;
if(args.Length < 1)
{
port = 8080;
}
else
{
try
{
port = Int32.Parse(args[0]);
}
catch
{
port = 8080;
}
}
// --- if correct number of arguments
if (args.Length == 1)
{
ChatEngine server = new ChatEngine(port);
}
else
{
// otherwise give correct usage
Console.Out.WriteLine("Usage: chatsrv [port]");
}
}
}
}