fixed bugs

This commit is contained in:
princessbobsanta 2016-04-13 01:20:00 -10:00
commit 0e82467079
18 changed files with 394 additions and 546 deletions

View File

@ -48,6 +48,7 @@ namespace GameCreatorGroupProject
reader = new StreamReader(stream); reader = new StreamReader(stream);
//tells server clients username //tells server clients username
writer.WriteLine(MainClient.getUsername()); writer.WriteLine(MainClient.getUsername());
writer.Flush();
} }
else else
{ {

View File

@ -1,114 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GameCreatorGroupProject
{
class ChatServer : TCPServer
{
private List<TcpClient> clientList = new List<TcpClient>();
private Dictionary<IPAddress, string> collaborators;
private bool running = true;
//chat port
private readonly int port = 20113;
//starts a chat server
public override void startServer(Project project)
{
//gets collaborator list from project
collaborators = project.Collaborators;
//attempts to start listener on chat port
try
{
//possible issues with conflicts if multiple chat servers running, to be fixed later
listener = new TcpListener(IPAddress.Any, port);
listener.Start();
}
//displays error box if unable to start server
catch (SocketException e)
{
MessageBox.Show("A network error has occured.", "Unable to start chat server.", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
//main server control
while (running)
{
//checks if a new client is waiting to connect
if (listener.Pending())
{
//connects to client
//currently connects to any client, possibly add security later
TcpClient client = listener.AcceptTcpClient();
clientList.Add(client);
//spawns new thread for handling data transmission to other clients
Thread t = new Thread(transmitter);
t.Start(client);
}
}
}
//sends messages to all clients
private void transmitter(Object client)
{
using (TcpClient thisClient = (TcpClient)client)
{
NetworkStream inStream = ((TcpClient)client).GetStream();
StringBuilder message = new StringBuilder();
StreamReader reader = new StreamReader(inStream);
StreamWriter writer = null;
NetworkStream outStream;
while (thisClient.Connected && running)
{
//checks if data is available on the clients stream
if (inStream.DataAvailable)
{
//sends data to all clients in chat
foreach (TcpClient c in clientList)
{
message.Clear();
IPAddress userIP;
string clientName;
//gets client IP, used to determine client name (to be changed)
userIP = ((IPEndPoint)thisClient.Client.RemoteEndPoint).Address;
//creates StreamWriter for current outgoing client
outStream = c.GetStream();
writer = new StreamWriter(outStream);
//appends sender name to beginning of message
collaborators.TryGetValue(userIP, out clientName);
message.Append(clientName);
message.Append(": ");
//appends outgoing message
message.Append(reader.ReadLine());
//writes message to outgoing stream
writer.WriteLine(message.ToString());
writer.Flush();
}
}
}
if (writer != null) { writer.Close(); }
if (reader != null) { reader.Close(); }
lock (clientList)
{
clientList.Remove(thisClient);
}
}
}
public override void stopServer()
{
if (listener != null) { listener.Stop(); }
running = false;
}
}
}

View File

@ -41,6 +41,7 @@
this.itemStartServer = new System.Windows.Forms.ToolStripMenuItem(); this.itemStartServer = new System.Windows.Forms.ToolStripMenuItem();
this.itemConnect = new System.Windows.Forms.ToolStripMenuItem(); this.itemConnect = new System.Windows.Forms.ToolStripMenuItem();
this.itemDisconnect = new System.Windows.Forms.ToolStripMenuItem(); this.itemDisconnect = new System.Windows.Forms.ToolStripMenuItem();
this.sendMessageToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.statusStrip1 = new System.Windows.Forms.StatusStrip(); this.statusStrip1 = new System.Windows.Forms.StatusStrip();
this.ModeControlTabs = new System.Windows.Forms.TabControl(); this.ModeControlTabs = new System.Windows.Forms.TabControl();
this.ResourcesTab = new System.Windows.Forms.TabPage(); this.ResourcesTab = new System.Windows.Forms.TabPage();
@ -152,6 +153,9 @@
this.txtMessage = new System.Windows.Forms.TextBox(); this.txtMessage = new System.Windows.Forms.TextBox();
this.txtChat = new System.Windows.Forms.TextBox(); this.txtChat = new System.Windows.Forms.TextBox();
this.folderPrjDir = new System.Windows.Forms.FolderBrowserDialog(); this.folderPrjDir = new System.Windows.Forms.FolderBrowserDialog();
this.addUserToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.addUserDebugToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.addUserReleaseToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStrip1.SuspendLayout(); this.toolStrip1.SuspendLayout();
this.ModeControlTabs.SuspendLayout(); this.ModeControlTabs.SuspendLayout();
this.ResourcesTab.SuspendLayout(); this.ResourcesTab.SuspendLayout();
@ -242,12 +246,14 @@
this.toolChat.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolChat.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.itemStartServer, this.itemStartServer,
this.itemConnect, this.itemConnect,
this.itemDisconnect}); this.itemDisconnect,
this.sendMessageToolStripMenuItem,
this.addUserToolStripMenuItem});
this.toolChat.ForeColor = System.Drawing.SystemColors.ControlLight; this.toolChat.ForeColor = System.Drawing.SystemColors.ControlLight;
this.toolChat.Image = ((System.Drawing.Image)(resources.GetObject("toolChat.Image"))); this.toolChat.Image = ((System.Drawing.Image)(resources.GetObject("toolChat.Image")));
this.toolChat.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolChat.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolChat.Name = "toolChat"; this.toolChat.Name = "toolChat";
this.toolChat.Size = new System.Drawing.Size(78, 22); this.toolChat.Size = new System.Drawing.Size(77, 22);
this.toolChat.Text = "Team Chat"; this.toolChat.Text = "Team Chat";
// //
// itemStartServer // itemStartServer
@ -270,6 +276,13 @@
this.itemDisconnect.Size = new System.Drawing.Size(177, 22); this.itemDisconnect.Size = new System.Drawing.Size(177, 22);
this.itemDisconnect.Text = "Disconnect..."; this.itemDisconnect.Text = "Disconnect...";
// //
// sendMessageToolStripMenuItem
//
this.sendMessageToolStripMenuItem.Name = "sendMessageToolStripMenuItem";
this.sendMessageToolStripMenuItem.Size = new System.Drawing.Size(177, 22);
this.sendMessageToolStripMenuItem.Text = "Send Message";
this.sendMessageToolStripMenuItem.Click += new System.EventHandler(this.sendMessageToolStripMenuItem_Click);
//
// statusStrip1 // statusStrip1
// //
this.statusStrip1.BackColor = System.Drawing.SystemColors.ControlDarkDark; this.statusStrip1.BackColor = System.Drawing.SystemColors.ControlDarkDark;
@ -1503,7 +1516,7 @@
// btnSendMsg // btnSendMsg
// //
this.btnSendMsg.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnSendMsg.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnSendMsg.Location = new System.Drawing.Point(1016, 141); this.btnSendMsg.Location = new System.Drawing.Point(1016, 133);
this.btnSendMsg.Name = "btnSendMsg"; this.btnSendMsg.Name = "btnSendMsg";
this.btnSendMsg.Size = new System.Drawing.Size(139, 23); this.btnSendMsg.Size = new System.Drawing.Size(139, 23);
this.btnSendMsg.TabIndex = 2; this.btnSendMsg.TabIndex = 2;
@ -1514,7 +1527,7 @@
// //
this.txtMessage.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) this.txtMessage.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right))); | System.Windows.Forms.AnchorStyles.Right)));
this.txtMessage.Location = new System.Drawing.Point(3, 141); this.txtMessage.Location = new System.Drawing.Point(3, 133);
this.txtMessage.Name = "txtMessage"; this.txtMessage.Name = "txtMessage";
this.txtMessage.Size = new System.Drawing.Size(1006, 20); this.txtMessage.Size = new System.Drawing.Size(1006, 20);
this.txtMessage.TabIndex = 1; this.txtMessage.TabIndex = 1;
@ -1529,7 +1542,7 @@
this.txtChat.Name = "txtChat"; this.txtChat.Name = "txtChat";
this.txtChat.ReadOnly = true; this.txtChat.ReadOnly = true;
this.txtChat.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.txtChat.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.txtChat.Size = new System.Drawing.Size(1152, 132); this.txtChat.Size = new System.Drawing.Size(1152, 124);
this.txtChat.TabIndex = 0; this.txtChat.TabIndex = 0;
// //
// folderPrjDir // folderPrjDir
@ -1537,6 +1550,30 @@
this.folderPrjDir.Description = "Specify a folder to store the project in:"; this.folderPrjDir.Description = "Specify a folder to store the project in:";
this.folderPrjDir.RootFolder = System.Environment.SpecialFolder.MyDocuments; this.folderPrjDir.RootFolder = System.Environment.SpecialFolder.MyDocuments;
// //
// addUserToolStripMenuItem
//
this.addUserToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.addUserDebugToolStripMenuItem,
this.addUserReleaseToolStripMenuItem});
this.addUserToolStripMenuItem.Name = "addUserToolStripMenuItem";
this.addUserToolStripMenuItem.Size = new System.Drawing.Size(177, 22);
this.addUserToolStripMenuItem.Text = "Add User";
this.addUserToolStripMenuItem.Click += new System.EventHandler(this.addUserToolStripMenuItem_Click);
//
// addUserDebugToolStripMenuItem
//
this.addUserDebugToolStripMenuItem.Name = "addUserDebugToolStripMenuItem";
this.addUserDebugToolStripMenuItem.Size = new System.Drawing.Size(164, 22);
this.addUserDebugToolStripMenuItem.Text = "Add User Debug";
this.addUserDebugToolStripMenuItem.Click += new System.EventHandler(this.addUserDebugToolStripMenuItem_Click);
//
// addUserReleaseToolStripMenuItem
//
this.addUserReleaseToolStripMenuItem.Name = "addUserReleaseToolStripMenuItem";
this.addUserReleaseToolStripMenuItem.Size = new System.Drawing.Size(164, 22);
this.addUserReleaseToolStripMenuItem.Text = "Add User Release";
this.addUserReleaseToolStripMenuItem.Click += new System.EventHandler(this.addUserReleaseToolStripMenuItem_Click);
//
// MainWindow // MainWindow
// //
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
@ -1712,7 +1749,11 @@
private System.Windows.Forms.ToolStripMenuItem itemConnect; private System.Windows.Forms.ToolStripMenuItem itemConnect;
private System.Windows.Forms.ToolStripMenuItem itemStartServer; private System.Windows.Forms.ToolStripMenuItem itemStartServer;
private System.Windows.Forms.ToolStripDropDownButton toolChat; private System.Windows.Forms.ToolStripDropDownButton toolChat;
private System.Windows.Forms.FolderBrowserDialog folderPrjDir; private System.Windows.Forms.FolderBrowserDialog folderPrjDir;
private System.Windows.Forms.ToolStripMenuItem sendMessageToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem addUserToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem addUserDebugToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem addUserReleaseToolStripMenuItem;
} }
} }

View File

@ -34,6 +34,8 @@ namespace GameCreatorGroupProject
MainClient online; MainClient online;
TCPClient chat; TCPClient chat;
private uint chatServerID;
// Declare a ResourceImporter to make it easier to load and save resources // Declare a ResourceImporter to make it easier to load and save resources
ResourceImporter resImporter = new ResourceImporter(); ResourceImporter resImporter = new ResourceImporter();
@ -186,7 +188,7 @@ namespace GameCreatorGroupProject
openResourceDialog.ShowDialog(); openResourceDialog.ShowDialog();
// Restore filter to unfiltered state // Restore filter to unfiltered state
openResourceDialog.Filter = "All Files (*.*)|*.*"; openResourceDialog.Filter = "All Files (*.*)|*.*";
// Grab user-selected path // Grab user-selected path
string projPath = openResourceDialog.FileName; string projPath = openResourceDialog.FileName;
@ -205,8 +207,11 @@ namespace GameCreatorGroupProject
private void itemConnect_Click(object sender, EventArgs e) private void itemConnect_Click(object sender, EventArgs e)
{ {
uint chatServerID = online.requestChatServer(); chatServerID = online.requestChatServer();
chat = MainClient.clients.ElementAt(0); MessageBox.Show("Connected to chat server: " + chatServerID.ToString());
//online.connectClient(1, chatServerID, 1);
//chat = MainClient.clients.ElementAt(0);
//chat.connectClient(ServerInfo.getServerIP());
} }
private void MainWindow_Load(object sender, EventArgs e) private void MainWindow_Load(object sender, EventArgs e)
@ -235,7 +240,24 @@ namespace GameCreatorGroupProject
{ {
string msg = "Hello World!"; string msg = "Hello World!";
object temp = msg; object temp = msg;
if (chat == null)
chat = online.getAvailable();
chat.send(ref temp); chat.send(ref temp);
} }
private void addUserToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void addUserDebugToolStripMenuItem_Click(object sender, EventArgs e)
{
online.connectClient(1, chatServerID, 0);
}
private void addUserReleaseToolStripMenuItem_Click(object sender, EventArgs e)
{
online.connectClient(1, chatServerID, 1);
}
} }
} }

View File

@ -1,57 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.Threading;
namespace Room
{
class GEngine
{
/*______________members_________________________________*/
private Graphics drawHandle;
private Thread renderThread;
/*______________functions_______________________________*/
public GEngine(Graphics g)
{
drawHandle = g;
}
public void init()
{
renderThread = new Thread(new ThreadStart(render));
renderThread.Start();
}
public void stop()
{
renderThread.Abort();
}
private void render()
{
int framesRendered = 0;
long startTime = Environment.TickCount;
while (true)
{
drawHandle.FillRectangle(new SolidBrush(Color.Yellow), 0, 0, 1200, 700);
//benchmarking
framesRendered++;
if((Environment.TickCount) >= startTime + 1000)
{
Console.WriteLine("GEngine: " + framesRendered + " fps");
framesRendered = 0;
startTime = Environment.TickCount;
}
}
}
}
}

View File

@ -51,13 +51,18 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="ChatClient.cs" /> <Compile Include="ChatClient.cs" />
<Compile Include="ChatServer.cs" />
<Compile Include="Form1.cs"> <Compile Include="Form1.cs">
<SubType>Form</SubType> <SubType>Form</SubType>
</Compile> </Compile>
<Compile Include="Form1.Designer.cs"> <Compile Include="Form1.Designer.cs">
<DependentUpon>Form1.cs</DependentUpon> <DependentUpon>Form1.cs</DependentUpon>
</Compile> </Compile>
<Compile Include="Form2.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="Form2.Designer.cs">
<DependentUpon>Form2.cs</DependentUpon>
</Compile>
<Compile Include="MainClient.cs" /> <Compile Include="MainClient.cs" />
<Compile Include="notConnectedException.cs" /> <Compile Include="notConnectedException.cs" />
<Compile Include="Object.cs" /> <Compile Include="Object.cs" />
@ -70,10 +75,12 @@
<Compile Include="Segment.cs" /> <Compile Include="Segment.cs" />
<Compile Include="ServerInfo.cs" /> <Compile Include="ServerInfo.cs" />
<Compile Include="TCPClient.cs" /> <Compile Include="TCPClient.cs" />
<Compile Include="TCPServer.cs" />
<EmbeddedResource Include="Form1.resx"> <EmbeddedResource Include="Form1.resx">
<DependentUpon>Form1.cs</DependentUpon> <DependentUpon>Form1.cs</DependentUpon>
</EmbeddedResource> </EmbeddedResource>
<EmbeddedResource Include="Form2.resx">
<DependentUpon>Form2.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Properties\Resources.resx"> <EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator> <Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput> <LastGenOutput>Resources.Designer.cs</LastGenOutput>

View File

@ -11,9 +11,19 @@ namespace GameCreatorGroupProject
internal class MainClient internal class MainClient
{ {
//TEMPORARY, each program should have unique clientID //TEMPORARY, each program should have unique clientID
#if DEBUG
private static readonly uint thisClientID = 0; private static readonly uint thisClientID = 0;
#else
private static readonly uint thisClientID = 1;
#endif
//have some way for user to provide username //have some way for user to provide username
private static string username = ""; #if DEBUG
private static string username = "Debug";
#else
private static string username = "Release";
#endif
public static List<TCPClient> clients = new List<TCPClient>(); public static List<TCPClient> clients = new List<TCPClient>();
@ -68,7 +78,7 @@ namespace GameCreatorGroupProject
} }
//connects to specified chat server //connects to specified chat server
public TCPClient connectClient(string serverIP) public void connectClient(string serverIP)
{ {
TCPClient c = null; TCPClient c = null;
dc = false; dc = false;
@ -113,7 +123,6 @@ namespace GameCreatorGroupProject
{ {
//reads stream data //reads stream data
connectInfo = new Tuple<byte, uint>(reader.ReadByte(), reader.ReadUInt32()); connectInfo = new Tuple<byte, uint>(reader.ReadByte(), reader.ReadUInt32());
c = null;
//creates requested client //creates requested client
//might need to add way to control clients (eg disconnect, etc), probably add to a list or somthing //might need to add way to control clients (eg disconnect, etc), probably add to a list or somthing
switch (connectInfo.Item1) switch (connectInfo.Item1)
@ -144,7 +153,6 @@ namespace GameCreatorGroupProject
disconnect(); disconnect();
MessageBox.Show("A network error has occured.", "Unable to connect to server.", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("A network error has occured.", "Unable to connect to server.", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
return c;
} }

View File

@ -1,24 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GameCreatorGroupProject
{
abstract class TCPServer
{
protected TcpListener listener = null;
//starts the server for use with the specified project
abstract public void startServer(Project project);
//stops the server
abstract public void stopServer();
}
}

View File

@ -1,27 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
namespace Room
{
class Game
{
private GEngine gEngine;
public void startGraphics(Graphics g)
{
gEngine = new GEngine(g);
gEngine.init();
}
public void stopGame()
{
gEngine.stop();
}
}
}

View File

@ -19,3 +19,6 @@ C:\Users\Jared\Documents\GitHub\CS-350-410-431-Group-Project\OpenTK-Test\JustThe
C:\Users\Jared\Documents\GitHub\CS-350-410-431-Group-Project\OpenTK-Test\JustTheBasics\obj\Debug\JustTheBasics.csprojResolveAssemblyReference.cache C:\Users\Jared\Documents\GitHub\CS-350-410-431-Group-Project\OpenTK-Test\JustTheBasics\obj\Debug\JustTheBasics.csprojResolveAssemblyReference.cache
C:\Users\Jared\Documents\GitHub\CS-350-410-431-Group-Project\OpenTK-Test\JustTheBasics\obj\Debug\JustTheBasics.exe C:\Users\Jared\Documents\GitHub\CS-350-410-431-Group-Project\OpenTK-Test\JustTheBasics\obj\Debug\JustTheBasics.exe
C:\Users\Jared\Documents\GitHub\CS-350-410-431-Group-Project\OpenTK-Test\JustTheBasics\obj\Debug\JustTheBasics.pdb C:\Users\Jared\Documents\GitHub\CS-350-410-431-Group-Project\OpenTK-Test\JustTheBasics\obj\Debug\JustTheBasics.pdb
C:\Users\Jared\Documents\GitHub\mod13\OpenTK-Test\JustTheBasics\bin\Debug\JustTheBasics.exe.config
C:\Users\Jared\Documents\GitHub\mod13\OpenTK-Test\JustTheBasics\obj\Debug\JustTheBasics.exe
C:\Users\Jared\Documents\GitHub\mod13\OpenTK-Test\JustTheBasics\obj\Debug\JustTheBasics.pdb

View File

@ -14,6 +14,9 @@ namespace Server_application
{ {
class ChatServer : TCPServer class ChatServer : TCPServer
{ {
protected static TcpListener listener = null;
protected static bool listenerStarted = false;
private static uint currentID = 0; private static uint currentID = 0;
public static readonly object IDLock = new object(); public static readonly object IDLock = new object();
private Dictionary<TcpClient, string> clientList = new Dictionary<TcpClient, string>(); private Dictionary<TcpClient, string> clientList = new Dictionary<TcpClient, string>();
@ -54,16 +57,21 @@ namespace Server_application
public override void startServer() public override void startServer()
{ {
//attempts to start listener on chat port //attempts to start listener on chat port
try if (!listenerStarted)
{ {
listener = new TcpListener(IPAddress.Any, port); try
listener.Start(); {
} listener = new TcpListener(IPAddress.Any, port);
//displays error box if unable to start server listener.Start();
catch (SocketException e) listenerStarted = true;
{ }
MessageBox.Show("A network error has occured.", "Unable to start chat server.", MessageBoxButtons.OK, MessageBoxIcon.Error); //displays error box if unable to start server
catch (SocketException e)
{
MessageBox.Show("A network error has occured.", "Unable to start chat server.", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
} }
//server control loop //server control loop
while (running) while (running)
{ {
@ -106,10 +114,10 @@ namespace Server_application
//checks if data is available on the clients stream //checks if data is available on the clients stream
if (inStream.DataAvailable) if (inStream.DataAvailable)
{ {
message = reader.ReadLine();
//sends data to all clients in chat //sends data to all clients in chat
foreach (KeyValuePair<TcpClient, string> c in clientList) foreach (KeyValuePair<TcpClient, string> c in clientList)
{ {
message = "";
string clientName; string clientName;
//creates StreamWriter for current outgoing client //creates StreamWriter for current outgoing client
@ -117,7 +125,6 @@ namespace Server_application
writer = new StreamWriter(outStream); writer = new StreamWriter(outStream);
//appends sender name to beginning of message //appends sender name to beginning of message
clientList.TryGetValue(thisClient, out clientName); clientList.TryGetValue(thisClient, out clientName);
message = reader.ReadLine();
//writes sender and message to outgoing stream //writes sender and message to outgoing stream
writer.WriteLine(clientName + ": " + message.ToString()); writer.WriteLine(clientName + ": " + message.ToString());
writer.Flush(); writer.Flush();

View File

@ -1,274 +1,280 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
using System.Net.Sockets; using System.Net.Sockets;
using System.Text; using System.Text;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
namespace Server_application namespace Server_application
{ {
class MainServer : TCPServer class MainServer : TCPServer
{ {
//dictionary of connected clients by clientID protected static TcpListener listener = null;
private Dictionary<uint, TcpClient> clientList = new Dictionary<uint, TcpClient>(); protected static bool listenerStarted = false;
private bool running = true;
private static readonly object serverCounterLock = new Object(); //dictionary of connected clients by clientID
private uint serverCounter = 0; private Dictionary<uint, TcpClient> clientList = new Dictionary<uint, TcpClient>();
//main server port private bool running = true;
private readonly int port = 20112; private static readonly object serverCounterLock = new Object();
private uint serverCounter = 0;
public override void startServer() //main server port
{ private readonly int port = 20112;
//attempts to start listener on chat port
try public override void startServer()
{ {
//possible issues with conflicts if multiple chat servers running, to be fixed later //attempts to start listener on chat port
listener = new TcpListener(IPAddress.Any, port); if (!listenerStarted)
listener.Start(); {
} try
//displays error box if unable to start server {
catch (SocketException e) //possible issues with conflicts if multiple chat servers running, to be fixed later
{ listener = new TcpListener(IPAddress.Any, port);
MessageBox.Show("A network error has occured.", "Unable to start chat server.", MessageBoxButtons.OK, MessageBoxIcon.Error); listener.Start();
} }
//main server control //displays error box if unable to start server
while (running) catch (SocketException e)
{ {
//checks if a new client is waiting to connect MessageBox.Show("A network error has occured.", "Unable to start chat server.", MessageBoxButtons.OK, MessageBoxIcon.Error);
if (listener.Pending()) }
{ }
//connects to client //main server control
//currently connects to any client, possibly add security later while (running)
TcpClient client = listener.AcceptTcpClient(); {
NetworkStream stream = client.GetStream(); //checks if a new client is waiting to connect
BinaryReader reader = new BinaryReader(stream); if (listener.Pending())
byte type = reader.ReadByte(); {
//connects to client
//client type sends requests to server //currently connects to any client, possibly add security later
if (type == 0) TcpClient client = listener.AcceptTcpClient();
{ NetworkStream stream = client.GetStream();
Thread t = new Thread(transmitter); BinaryReader reader = new BinaryReader(stream);
t.Start(client); byte type = reader.ReadByte();
}
//client type waits for requests from server //client type sends requests to server
else if (type == 1) if (type == 0)
{ {
uint thisClientID = reader.ReadUInt32(); Thread t = new Thread(transmitter);
//adds client to a dictionary for use t.Start(client);
clientList.Add(thisClientID, client); }
} //client type waits for requests from server
} else if (type == 1)
} {
} uint thisClientID = reader.ReadUInt32();
//adds client to a dictionary for use
//communicates between clients clientList.Add(thisClientID, client);
private void transmitter(Object client) }
{ }
using (TcpClient thisClient = (TcpClient)client) }
{ }
NetworkStream stream = thisClient.GetStream();
BinaryReader reader = new BinaryReader(stream); //communicates between clients
BinaryWriter writer = new BinaryWriter(stream); private void transmitter(Object client)
{
uint thisClientID = reader.ReadUInt32(); using (TcpClient thisClient = (TcpClient)client)
{
//control while client connected and server running NetworkStream stream = thisClient.GetStream();
while (thisClient.Connected && running) BinaryReader reader = new BinaryReader(stream);
{ BinaryWriter writer = new BinaryWriter(stream);
//checks if data is available on the clients stream
if (stream.DataAvailable) uint thisClientID = reader.ReadUInt32();
{
//gets the type of request sent by the client //control while client connected and server running
byte reqType = reader.ReadByte(); while (thisClient.Connected && running)
switch (reqType) {
{ //checks if data is available on the clients stream
//request for chat server if (stream.DataAvailable)
case 1: {
//locks to ensure server counter not modified by another thread //gets the type of request sent by the client
lock (serverCounterLock) byte reqType = reader.ReadByte();
{ switch (reqType)
//increments server counter {
serverCounter++; //request for chat server
//creates chat server with serverCounter as its ID in new thread case 1:
Thread tC = new Thread(startChatServer); //locks to ensure server counter not modified by another thread
tC.Start(serverCounter); lock (serverCounterLock)
//writes the assigned serverID to client {
writer.Write(serverCounter); //increments server counter
} serverCounter++;
break; //creates chat server with serverCounter as its ID in new thread
//request for resource server Thread tC = new Thread(startChatServer);
case 2: tC.Start(serverCounter);
//locks to ensure server counter not modified by another thread //writes the assigned serverID to client
lock (serverCounterLock) writer.Write(serverCounter);
{ }
//increments server counter break;
serverCounter++; //request for resource server
//creates resource server with serverCounter as its ID in new thread case 2:
Thread tR = new Thread(startResourceServer); //locks to ensure server counter not modified by another thread
tR.Start(serverCounter); lock (serverCounterLock)
//writes the assigned serverID to client {
writer.Write(serverCounter); //increments server counter
} serverCounter++;
break; //creates resource server with serverCounter as its ID in new thread
//request for real time collaboration server Thread tR = new Thread(startResourceServer);
case 3: tR.Start(serverCounter);
//locks to ensure server counter not modified by another thread //writes the assigned serverID to client
lock (serverCounterLock) writer.Write(serverCounter);
{ }
//increments server counter break;
serverCounter++; //request for real time collaboration server
//creates real time collaboration server with serverCounter as its ID in new thread case 3:
Thread tRTC = new Thread(startRTCServer); //locks to ensure server counter not modified by another thread
tRTC.Start(serverCounter); lock (serverCounterLock)
//writes the assigned serverID to client {
writer.Write(serverCounter); //increments server counter
} serverCounter++;
break; //creates real time collaboration server with serverCounter as its ID in new thread
//request to connect a client to a server Thread tRTC = new Thread(startRTCServer);
case 4: tRTC.Start(serverCounter);
TcpClient connect; //writes the assigned serverID to client
//reads connection info from stream writer.Write(serverCounter);
byte serType = reader.ReadByte(); }
uint serverID = reader.ReadUInt32(); break;
uint clientID = reader.ReadUInt32(); //request to connect a client to a server
//checks if specified client connected, and gets corresponding TcpClient case 4:
if (clientList.TryGetValue(clientID, out connect)) TcpClient connect;
{ //reads connection info from stream
//creates reader and writer on requested clients stream byte serType = reader.ReadByte();
NetworkStream cStream = connect.GetStream(); uint serverID = reader.ReadUInt32();
BinaryWriter cWriter = new BinaryWriter(cStream); uint clientID = reader.ReadUInt32();
//checks the type of server connection request for //checks if specified client connected, and gets corresponding TcpClient
switch (serType) if (clientList.TryGetValue(clientID, out connect))
{ {
//connection request for chat server //creates reader and writer on requested clients stream
case 1: NetworkStream cStream = connect.GetStream();
//locks to ensure ChatServer's currentID is not changed BinaryWriter cWriter = new BinaryWriter(cStream);
lock (ChatServer.IDLock) //checks the type of server connection request for
{ switch (serType)
//tells chat servers listener that incoming request is for server with specified ID {
ChatServer.setCurrentID(serverID); //connection request for chat server
//tells chat server that a connection is expected case 1:
ChatServer.setConnectExpected(); //locks to ensure ChatServer's currentID is not changed
//tells client to connect lock (ChatServer.IDLock)
cWriter.Write(serType); {
cWriter.Write(serverID); //tells chat servers listener that incoming request is for server with specified ID
//waits for client to connect to unlock, connectExpected set to false when it does ChatServer.setCurrentID(serverID);
while (ChatServer.getConnectExpected() && connect.Connected) { } //tells chat server that a connection is expected
} ChatServer.setConnectExpected();
break; //tells client to connect
//connection request for resource server cWriter.Write(serType);
case 2: cWriter.Write(serverID);
//structure same as chat server, see comments for case 1 //waits for client to connect to unlock, connectExpected set to false when it does
lock (ResourceServer.IDLock) while (ChatServer.getConnectExpected() && connect.Connected) { }
{ }
ResourceServer.setCurrentID(serverID); break;
ResourceServer.setConnectExpected(); //connection request for resource server
cWriter.Write(serType); case 2:
cWriter.Write(serverID); //structure same as chat server, see comments for case 1
while (ResourceServer.getConnectExpected() && connect.Connected) { } lock (ResourceServer.IDLock)
} {
break; ResourceServer.setCurrentID(serverID);
//connection request for real time collaboration server ResourceServer.setConnectExpected();
case 3: cWriter.Write(serType);
//structure same as chat server, see comments for case 1 cWriter.Write(serverID);
lock (RTCServer.IDLock) while (ResourceServer.getConnectExpected() && connect.Connected) { }
{ }
RTCServer.setCurrentID(serverID); break;
RTCServer.setConnectExpected(); //connection request for real time collaboration server
cWriter.Write(serType); case 3:
cWriter.Write(serverID); //structure same as chat server, see comments for case 1
while (RTCServer.getConnectExpected() && connect.Connected) { } lock (RTCServer.IDLock)
} {
break; RTCServer.setCurrentID(serverID);
} RTCServer.setConnectExpected();
//checks if requested client still connected cWriter.Write(serType);
if (connect.Connected) cWriter.Write(serverID);
{ while (RTCServer.getConnectExpected() && connect.Connected) { }
//tells requester client successfully connected if it is }
writer.Write(true); break;
} }
else //checks if requested client still connected
{ if (connect.Connected)
//else indicates connection unsuccessful {
writer.Write(false); //tells requester client successfully connected if it is
} writer.Write(true);
}
} else
//requested client not connected {
else //else indicates connection unsuccessful
{ writer.Write(false);
//tells client connection request was unsuccessful }
writer.Write(false);
} }
//requested client not connected
break; else
//request for status of indicated client {
case 5: //tells client connection request was unsuccessful
TcpClient temp; writer.Write(false);
//checks if indicated client is in list of connected clients }
if (clientList.TryGetValue(reader.ReadUInt32(), out temp))
{ break;
//tells requester specified client is connected //request for status of indicated client
writer.Write(true); case 5:
} TcpClient temp;
else //checks if indicated client is in list of connected clients
{ if (clientList.TryGetValue(reader.ReadUInt32(), out temp))
//tells requester specified client is not connected {
writer.Write(false); //tells requester specified client is connected
} writer.Write(true);
break; }
else
} {
} //tells requester specified client is not connected
} writer.Write(false);
}
//cleanup break;
if (writer != null) { writer.Close(); }
if (reader != null) { reader.Close(); } }
//removes client from list of connected clients }
lock (clientList) }
{
TcpClient close; //cleanup
if (clientList.TryGetValue(thisClientID, out close)) if (writer != null) { writer.Close(); }
{ if (reader != null) { reader.Close(); }
close.GetStream().Close(); //removes client from list of connected clients
close.Close(); lock (clientList)
clientList.Remove(thisClientID); {
} TcpClient close;
} if (clientList.TryGetValue(thisClientID, out close))
} {
} close.GetStream().Close();
close.Close();
//starts a real time collaboration server with specidied serverID clientList.Remove(thisClientID);
private void startRTCServer(object serverID) }
{ }
TCPServer server = new RTCServer((uint)serverID); }
server.startServer(); }
}
//starts a real time collaboration server with specidied serverID
//starts a resource server with specidied serverID private void startRTCServer(object serverID)
private void startResourceServer(object serverID) {
{ TCPServer server = new RTCServer((uint)serverID);
TCPServer server = new ResourceServer((uint)serverID); server.startServer();
server.startServer(); }
}
//starts a resource server with specidied serverID
//starts a chat server with specidied serverID private void startResourceServer(object serverID)
private void startChatServer(object serverID) {
{ TCPServer server = new ResourceServer((uint)serverID);
TCPServer server = new ChatServer((uint)serverID); server.startServer();
server.startServer(); }
}
//starts a chat server with specidied serverID
//stops the main server private void startChatServer(object serverID)
public override void stopServer() {
{ TCPServer server = new ChatServer((uint)serverID);
if (listener != null) { listener.Stop(); } server.startServer();
running = false; }
}
} //stops the main server
} public override void stopServer()
{
if (listener != null) { listener.Stop(); }
running = false;
}
}
}

View File

@ -13,8 +13,6 @@ namespace Server_application
{ {
abstract class TCPServer abstract class TCPServer
{ {
protected TcpListener listener = null;
//starts the server for use with the specified project //starts the server for use with the specified project
abstract public void startServer(); abstract public void startServer();

View File

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
</configuration>

View File

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
</configuration>

View File

@ -1,11 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
<requestedExecutionLevel level="asInvoker" uiAccess="false"/>
</requestedPrivileges>
</security>
</trustInfo>
</assembly>