Merged with UI Changes and NetworkController

This commit is contained in:
Patrick Hellebrand
2021-09-21 11:04:56 +02:00
11 changed files with 223 additions and 67 deletions

View File

@@ -12,10 +12,11 @@ namespace PolyChat
{ {
public class Controller public class Controller
{ {
public static IPAddress ip; public static string ip;
private MainPage UIController; private MainPage UIController;
private ClientHandler clientHandler; private ClientHandler clientHandler;
/*
public Controller(MainPage uiController) public Controller(MainPage uiController)
{ {
UIController = uiController; UIController = uiController;
@@ -30,9 +31,9 @@ namespace PolyChat
public void sendMessage(String ip, String name, String msg) public void sendMessage(String ip, String name, String msg)
{ {
clientHandler.getClient(ip).sendMessage(SendCode.Message, name, msg, DateTime.Now); clientHandler.getClient(ip).sendMessage(SendCode.Message, msg, DateTime.Now);
} }
*/
/// <summary> /// <summary>
/// prints out ip. on server side automatticaly finds 10.... ip (which is the correct one) /// prints out ip. on server side automatticaly finds 10.... ip (which is the correct one)
/// </summary> /// </summary>
@@ -93,11 +94,16 @@ namespace PolyChat
Console.WriteLine($"Message received from {socket.GetHashCode()}:{message.Data[0]}"); Console.WriteLine($"Message received from {socket.GetHashCode()}:{message.Data[0]}");
} }
static IPAddress[] GetIPs() static string[] GetIPs()
{ {
IPHostEntry ipEntry = Dns.GetHostEntry(Dns.GetHostName()); IPHostEntry ipEntry = Dns.GetHostEntry(Dns.GetHostName());
IPAddress[] addr = ipEntry.AddressList; IPAddress[] addr = ipEntry.AddressList;
return addr; string[] ips = new string[addr.Length];
for (int i=0; i<addr.Length; i++)
{
ips[i] = addr.ToString();
}
return ips;
} }
} }

View File

@@ -98,8 +98,8 @@
<ListView.ItemTemplate> <ListView.ItemTemplate>
<DataTemplate x:DataType="models:ChatMessage"> <DataTemplate x:DataType="models:ChatMessage">
<StackPanel x:Name="Message" Margin="0 4" Padding="16 8" CornerRadius="4" Background="{ThemeResource SystemAccentColor}"> <StackPanel x:Name="Message" Margin="0 4" Padding="16 8" CornerRadius="4" Background="{ThemeResource SystemAccentColor}">
<TextBlock Text="{x:Bind Text}"/> <TextBlock Text="{x:Bind Msg}"/>
<TextBlock Text="{x:Bind Date}"/> <TextBlock Text="{x:Bind StringTimeStamp}"/>
<TextBlock Text="{x:Bind Foreign}"/> <TextBlock Text="{x:Bind Foreign}"/>
</StackPanel> </StackPanel>
</DataTemplate> </DataTemplate>

View File

@@ -17,14 +17,15 @@ namespace PolyChat
/// </summary> /// </summary>
public sealed partial class MainPage : Page public sealed partial class MainPage : Page
{ {
private Controller Controller; private NetworkingController networkingController;
private ObservableCollection<ChatPartner> Partners; private ObservableCollection<ChatPartner> Partners;
private ChatPartner selectedPartner; private ChatPartner selectedPartner;
private string username; private string username;
public MainPage() public MainPage()
{ {
this.InitializeComponent(); this.InitializeComponent();
Controller = new Controller(this); networkingController = new NetworkingController(this);
Partners = new ObservableCollection<ChatPartner>(); Partners = new ObservableCollection<ChatPartner>();
//ipAddress.Text = IP.GetCodeFromIP(Controller.GetIP()); //ipAddress.Text = IP.GetCodeFromIP(Controller.GetIP());
} }
@@ -41,10 +42,9 @@ namespace PolyChat
{ {
selectedPartner.AddMessage(new ChatMessage( selectedPartner.AddMessage(new ChatMessage(
inputSend.Text, inputSend.Text,
DateTime.Now.ToString(),
false false
)); ));
Controller.sendMessage(selectedPartner.Code, username, inputSend.Text); networkingController.sendMessage(selectedPartner.Code, inputSend.Text);
// clear input // clear input
inputSend.Text = ""; inputSend.Text = "";
} }
@@ -79,13 +79,13 @@ namespace PolyChat
} }
} }
public void OnIncomingMessage(MSG message) public void OnIncomingMessage(ChatMessage message)
{ {
ChatPartner sendingPartner = Partners.First(p => p.Code == message.ip.ToString()); ChatPartner sendingPartner = Partners.First(p => p.Code == message.Ip);
sendingPartner.AddMessage(new ChatMessage( sendingPartner.AddMessage(new ChatMessage(
message.msg, message.Msg,
message.timestamp.ToString(), true,
true message.Sender
)); ));
} }

View File

@@ -1,23 +1,31 @@
namespace PolyChat.Models using System;
namespace PolyChat.Models
{ {
public class ChatMessage public class ChatMessage
{ {
public string Text; public readonly string Sender;
public string Date; public readonly DateTime Timestamp = new DateTime(1970, 01, 01);
public bool Foreign; public readonly string Msg = "empty";
public readonly string Ip;
public readonly bool Foreign;
public readonly string StringTimeStamp;
public ChatMessage(string text, string date, bool foreign) public ChatMessage(string Msg = "", bool Foreign = true, string Sender= "Unknown", string Ip = "127.0.0.1")
{ {
Text = text; this.Sender = Sender;
Date = date; this.Timestamp = DateTime.Now;
Foreign = foreign; StringTimeStamp = Timestamp.ToString();
this.Msg = Msg;
this.Foreign = Foreign;
this.Ip = Ip;
} }
override override
public string ToString() public string ToString()
{ {
string prefix = Foreign ? "Other" : "Me"; string prefix = Foreign ? "Other" : "Me";
return $"{prefix}: Text"; return $"{prefix}: {Msg}({Sender})";
} }
} }
} }

View File

@@ -10,31 +10,27 @@ using SocketIOSharp.Server.Client;
using EngineIOSharp.Common.Enum; using EngineIOSharp.Common.Enum;
using Json.Net; using Json.Net;
using System.Net; using System.Net;
using SocketIOSharp.Client;
using SocketIOSharp.Common;
using SocketIOSharp.Common.Packet; using SocketIOSharp.Common.Packet;
using System;
using System.Net;
using EngineIOSharp.Common.Enum;
using System.Threading; using System.Threading;
using PolyChat.Models.Exceptions;
namespace PolyChat.Models namespace PolyChat.Models
{ {
class Client class Client
{ {
private SocketIOClient connection; private SocketIOClient connection;
public Boolean isConnected = false; private Boolean connected = false;
private List<MSG> msgStack = new List<MSG>(); private String ipSelf;
private Boolean active = true;
private String ip;
public Client(SocketIOClient connection, String ip) public Client(SocketIOClient connection, String ip)
{ {
this.ip = ip; this.ipSelf = ip;
this.connection = connection; this.connection = connection;
InitEventHandlers(this, connection); InitEventHandlers(this, connection);
} }
//Sending
//===================================================================================
/// <summary> /// <summary>
/// converts String message into json file and sends it to the server. /// converts String message into json file and sends it to the server.
/// </summary> /// </summary>
@@ -44,12 +40,44 @@ namespace PolyChat.Models
/// <param name="sender">Sender of Message</param> /// <param name="sender">Sender of Message</param>
/// <param name="chatMessage">the accual text the user wants to send</param> /// <param name="chatMessage">the accual text the user wants to send</param>
/// <param name="timestamp">current time</param> /// <param name="timestamp">current time</param>
public void sendMessage(SendCode code, String sender, String chatMessage, DateTime timestamp) public void sendMessage(SendCode code, String chatMessage)
{ {
new Thread(() => new Thread(() =>
{ {
//create msg //create msg
MSG msg = new MSG(sender, Controller.ip, chatMessage, timestamp); ChatMessage msg = new ChatMessage(chatMessage, false, Controller.ip);
//convert msg
String petJson = JsonNet.Serialize(msg);
//wait if not connected and send msg
int i=0;
int sleeptimer = 2000;
while(!this.connected)
{
Thread.Sleep(sleeptimer);
i++;
if(i>=10)
{
throw new MessageTimedOutException(i*sleeptimer);
}
}
connection.Emit(code.ToString(), petJson);
}).Start();
}
/*
/// <summary>
/// Sends Message with new name
/// </summary>
/// <param name="code"></param>
/// <param name="nameChange"></param>
/// <param name="timestamp"></param>
public void sendNameChange(SendCode code, String nameChange)
{
new Thread(() =>
{
//create msg
ChatMessage msg = new ChatMessage( Controller.ip);
//convert msg //convert msg
String petJson = JsonNet.Serialize(msg); String petJson = JsonNet.Serialize(msg);
@@ -58,17 +86,12 @@ namespace PolyChat.Models
connection.Emit(code.ToString(), petJson); connection.Emit(code.ToString(), petJson);
}).Start(); }).Start();
} }
/*
private void recieveMessage(String msg)
{
// deserialize json string
MSG pet = JsonNet.Deserialize<MSG>(msg);
//TODO: send message to GUI
}
*/ */
//==================================================================================
//EventHandeling
//===================================================================================
/// <summary> /// <summary>
/// handles all events of client server communiation /// handles all events of client server communiation
/// </summary> /// </summary>
@@ -78,32 +101,32 @@ namespace PolyChat.Models
{ {
connection.On(SendCode.Message.ToString(), (Data) => connection.On(SendCode.Message.ToString(), (Data) =>
{ {
MSG pet = JsonNet.Deserialize<MSG>(BitConverter.ToString(Data[0].ToObject<byte[]>())); ChatMessage pet = JsonNet.Deserialize<ChatMessage>(BitConverter.ToString(Data[0].ToObject<byte[]>()));
//TODO: send message to GUI //TODO: send message to GUI
}); });
connection.On(SendCode.Command.ToString(), (Data) => connection.On(SendCode.Command.ToString(), (Data) =>
{ {
Console.WriteLine("Command recieved!" + Data[0]); Console.WriteLine("Command recieved!" + Data[0]);
}); });
connection.On(SendCode.test1.ToString(), (Data) =>
{
Console.WriteLine("test1 recieved!" + Data[0]);
});
connection.On(SendCode.test2.ToString(), (Data) =>
{
Console.WriteLine("test2 recieved!" + Data[0]);
});
connection.On(SocketIOEvent.CONNECTION, () => connection.On(SocketIOEvent.CONNECTION, () =>
{ {
Console.WriteLine("Connected!"); client.connected = true;
client.isConnected = true;
}); });
} }
//==================================================================================
//Getter and Setter
//==================================================================================
public String getIP() public String getIP()
{ {
return this.ip; return this.ipSelf;
}
public Boolean isConnected()
{
return this.connected;
} }
} }

View File

@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PolyChat.Models.Exceptions
{
public class MessageTimedOutException : Exception
{
public MessageTimedOutException(int seconds) : base(String.Format("After {0} seconds of trying to send the message it has timed out", seconds))
{
}
}
}

View File

@@ -18,7 +18,7 @@ namespace PolyChat.Models
public IPAddress ip = new IPAddress(new byte[] { 49,48,46,49,46,50,49,49,46,50,54 }); public IPAddress ip = new IPAddress(new byte[] { 49,48,46,49,46,50,49,49,46,50,54 });
public MSG(String sender, IPAddress ip, String msg, DateTime timestamp) public MSG(IPAddress ip, String msg, DateTime timestamp)
{ {
this.sender = sender; this.sender = sender;
this.ip = ip; this.ip = ip;

View File

@@ -0,0 +1,102 @@
using System;
using System.Collections.Generic;
using SocketIOSharp.Client;
using EngineIOSharp.Common.Enum;
using System.Net;
using PolyChat.Models.Exceptions;
namespace PolyChat.Models
{
class NetworkingController
{
public List<Client> clients = new List<Client>();
private String ownName = "";
private IPAddress ownIP;
MainPage uiController;
public NetworkingController (MainPage uiController)
{
this.uiController = uiController;
this.ownIP = getIP();
}
//EXTERNAL METHODS
//=========================================================================================================================================================================================
/// <summary>
/// connects self to server with given ip
/// </summary>
/// <param name="ip"> server to connect to </param>
public void connectNewClient(String ip)
{
SocketIOClient connection = new SocketIOClient(new SocketIOClientOption(EngineIOScheme.http, ip, 8050));
connection.Connect();
clients.Add(new Client(connection, ip));
}
/// <summary>
/// sends Message to given ip
/// </summary>
/// <param name="ip"> partner to send to </param>
/// <param name="msg"> to send </param>
public void sendMessage(String ip, String msg)
{
this.getClient(ip).sendMessage(SendCode.Message, msg);
}
/// <summary>
/// returns own ip adress
/// </summary>
/// <returns></returns>
public IPAddress getIP()
{
IPHostEntry ipEntry = Dns.GetHostEntry(Dns.GetHostName());
IPAddress[] addrList = ipEntry.AddressList;
for (short i = 0; i < addrList.Length; i++)
{
if (addrList[i].ToString().Substring(0, 3).Equals("10."))
{
return addrList[i];
}
}
return null;
}
/*
/// <summary>
/// changes name of self and sends new name to all chats
/// </summary>
/// <param name="newName"></param>
public void changeName(String newName)
{
this.ownName = newName;
foreach(Client cl in clients)
{
cl.sendNameChange(SendCode.NameChange, newName);
}
}
*/
//=========================================================================================================================================================================================
//INTERNAL METHODS
//=========================================================================================================================================================================================
/// <summary>
/// returns client that fits to ip adress
/// </summary>
/// <param name="ip"></param>
/// <returns></returns>
private Client getClient(String ip)
{
foreach (Client cl in clients)
{
if (cl.getIP().Equals(ip))
{
return cl;
}
}
return null;
}
}
}

View File

@@ -4,7 +4,7 @@
{ {
Message, Message,
Command, Command,
test1, NameChange,
test2 Initial
} }
} }

View File

@@ -14,7 +14,7 @@ namespace PolyChat.Models
{ {
private Controller p; private Controller p;
private readonly ushort Port; private readonly ushort Port;
private SocketIOServer Server; private SocketIOServer server;
private List<SocketIOSocket> Sockets = new List<SocketIOSocket>(); private List<SocketIOSocket> Sockets = new List<SocketIOSocket>();
/// <summary> /// <summary>
@@ -25,9 +25,9 @@ namespace PolyChat.Models
{ {
this.Port = Port; this.Port = Port;
this.p = p; this.p = p;
Server = new SocketIOServer(new SocketIOServerOption(Port)); server = new SocketIOServer(new SocketIOServerOption(Port));
Server.OnConnection((socket) => OnConnect(socket)); server.OnConnection((socket) => OnConnect(socket));
Server.Start(); server.Start();
Console.WriteLine($"Server started, binding to port {Port}, waiting for connection..."); Console.WriteLine($"Server started, binding to port {Port}, waiting for connection...");
} }

View File

@@ -12,7 +12,7 @@
<DefaultLanguage>en-US</DefaultLanguage> <DefaultLanguage>en-US</DefaultLanguage>
<TargetPlatformIdentifier>UAP</TargetPlatformIdentifier> <TargetPlatformIdentifier>UAP</TargetPlatformIdentifier>
<TargetPlatformVersion Condition=" '$(TargetPlatformVersion)' == '' ">10.0.19041.0</TargetPlatformVersion> <TargetPlatformVersion Condition=" '$(TargetPlatformVersion)' == '' ">10.0.19041.0</TargetPlatformVersion>
<TargetPlatformMinVersion>10.0.19041.0</TargetPlatformMinVersion> <TargetPlatformMinVersion>10.0.18362.0</TargetPlatformMinVersion>
<MinimumVisualStudioVersion>14</MinimumVisualStudioVersion> <MinimumVisualStudioVersion>14</MinimumVisualStudioVersion>
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids> <ProjectTypeGuids>{A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
@@ -124,10 +124,11 @@
</Compile> </Compile>
<Compile Include="Models\ChatMessage.cs" /> <Compile Include="Models\ChatMessage.cs" />
<Compile Include="Models\ChatPartner.cs" /> <Compile Include="Models\ChatPartner.cs" />
<Compile Include="Models\Exceptions\MessageTimedOutException.cs" />
<Compile Include="Models\NetworkingController.cs" />
<Compile Include="Models\Client.cs" /> <Compile Include="Models\Client.cs" />
<Compile Include="Models\ClientHandler.cs" /> <Compile Include="Models\ClientHandler.cs" />
<Compile Include="Models\Exceptions\ConnectionFailedException.cs" /> <Compile Include="Models\Exceptions\ConnectionFailedException.cs" />
<Compile Include="Models\MSG.cs" />
<Compile Include="Models\SendCode.cs" /> <Compile Include="Models\SendCode.cs" />
<Compile Include="Models\Socket.cs" /> <Compile Include="Models\Socket.cs" />
<Compile Include="Controller.cs" /> <Compile Include="Controller.cs" />