I've been working on a server in C# to get my skills up. So I wrote a multiuser multithreaded server using TcpServer and TcpClient
I'm not going to post all the code but I will post where most of it is
Networking.cs
/*
* User: Nelson
* Date: 1/28/2006
* Time: 9:07 PM
*/
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace Server
{
/// <summary>
/// Description of Networking.
/// </summary>
class Networking
{
TcpListener server;
ServerUsers users;
public void Net_Init()
{
server = new TcpListener(1460); // Depreciated, fix later
users = new ServerUsers(); // 100 Users
while (true)
{
server.Start();
if (server.Pending())
{
TcpClient newConnection = server.AcceptTcpClient();
Console.WriteLine("Server has recieved a connection.");
users.AddUser(newConnection);
}
}
}
}
}
ServerUsers.cs
/*
* User: Nelson
* Date: 1/29/2006
* Time: 3:04 AM
*/
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace Server
{
/// <summary>
/// Description of ServerUsers.
/// </summary>
public class ServerUsers
{
public ServerUsers()
{
// Initiate some misc objects here
}
public void AddUser(TcpClient c)
{
/* What we are going to do here
* is spawn a thread to the protocol
* handler which is a temporary place
* holder and it should fill in a
* user information structure which
* we canthen use to access thier information
* while they are chatting.
*/
/* Additional notes: Once that is done an array
* of UserInfo entries is kept here I guess
*/
Protocol tmpProto = new Protocol(c);
Thread myThread = new Thread(new ThreadStart(tmpProto.Run));
myThread.Start();
return;
}
}
}
Protocol.cs
/*
* User: Nelson
* Date: 1/30/2006
* Time: 1:14 AM
*/
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace Server
{
/// <summary>
/// Description of Protocol.
/// </summary>
public class Protocol
{
private TcpClient myClient;
private StreamReader SR;
private StreamWriter SW;
public Protocol(TcpClient c)
{
myClient = c;
SR = new StreamReader(myClient.GetStream());
SW = new StreamWriter(myClient.GetStream());
}
public void Run()
{
Console.WriteLine("Node spawned new thread, ready to commence protocol.");
SW.WriteLine("Hello world from C# Server!");
SW.Flush();
}
}
}
I'm going to extend this to include a protocol (probably textbased, may go binary using SW.Write())
I'm actually surprised at how simple it was.
Looking for suggestions/comments from people like Myndfyre and other .NET guru's