This commit is contained in:
Patrick Hellebrand
2021-09-21 13:29:33 +02:00
9 changed files with 143 additions and 115 deletions

View File

@@ -13,7 +13,7 @@ namespace PolyChat
public class Controller
{
public static string ip;
private MainPage UIController;
private readonly MainPage UIController;
private ClientHandler clientHandler;
/*
@@ -31,7 +31,7 @@ namespace PolyChat
public void sendMessage(String ip, String name, String msg)
{
clientHandler.getClient(ip).sendMessage(SendCode.Message, msg, DateTime.Now);
clientHandler.getClient(ip).send Message(SendCode.Message, msg, DateTime.Now);
}
*/
/// <summary>
@@ -61,7 +61,6 @@ namespace PolyChat
break;
}
}
Socket s = new Socket(this);
}
else if (input.Equals("client"))
{
@@ -72,34 +71,13 @@ namespace PolyChat
}
}
static void InitEventHandlers(SocketIOClient client)
{
client.On(SocketIOEvent.CONNECTION, () =>
{
Console.WriteLine("Connected!");
client.Emit("Message", "This is a Message Body!");
});
client.On(SocketIOEvent.DISCONNECT, () =>
{
Console.WriteLine();
Console.WriteLine("Disconnected!");
});
}
public void OnMessageCallback(SocketIOSocket socket, SocketIOAckEvent message)
{
Console.WriteLine($"Message received from {socket.GetHashCode()}:{message.Data[0]}");
}
static string[] GetIPs()
{
IPHostEntry ipEntry = Dns.GetHostEntry(Dns.GetHostName());
IPAddress[] addr = ipEntry.AddressList;
string[] ips = new string[addr.Length];
for (int i=0; i<addr.Length; i++)
for (int i = 0; i < addr.Length; i++)
{
ips[i] = addr.ToString();
}

View File

@@ -99,9 +99,9 @@
<ScrollViewer Grid.Row="1" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Hidden">
<ListView x:Name="listViewMessages" VerticalAlignment="Bottom" Margin="4 16">
<ListView.ItemTemplate>
<DataTemplate x:DataType="models:ChatMessage">
<DataTemplate x:DataType="models:Message">
<StackPanel x:Name="Message" Margin="0 4" Padding="16 8" CornerRadius="4" Background="{ThemeResource SystemAccentColor}">
<TextBlock Text="{x:Bind Content}"/>
<TextBlock Text="{x:Bind Msg}"/>
<TextBlock Text="{x:Bind Timestamp.ToShortDateString()}"/>
<TextBlock Text="{x:Bind Foreign}"/>
</StackPanel>

View File

@@ -59,10 +59,7 @@ namespace PolyChat
public void OnSendMessage(object sender = null, RoutedEventArgs e = null)
{
selectedPartner.AddMessage(new ChatMessage(
inputSend.Text,
false
));
selectedPartner.AddMessage(new Message(inputSend.Text,false));
networkingController.sendMessage(selectedPartner.Code, inputSend.Text);
// clear input
inputSend.Text = "";
@@ -97,11 +94,11 @@ namespace PolyChat
updateNoUsernamePlaceholder();
}
public void OnIncomingMessage(ChatMessage message)
public void OnIncomingMessage(Message message)
{
ChatPartner sendingPartner = Partners.First(p => p.Code == message.Ip);
sendingPartner.AddMessage(new ChatMessage(
message.Content,
sendingPartner.AddMessage(new Message(
message.Msg,
true,
message.Sender
));

View File

@@ -7,20 +7,20 @@ namespace PolyChat.Models
{
public string Name;
public string Code;
public ObservableCollection<ChatMessage> Messages;
public ObservableCollection<Message> Messages;
private SocketIOSocket socketIOSocket;
public ChatPartner(string name, string code, ObservableCollection<ChatMessage> messages = null)
public ChatPartner(string name, string code, ObservableCollection<Message> messages = null)
{
Name = name;
Code = code;
if (messages == null) Messages = new ObservableCollection<ChatMessage>();
if (messages == null) Messages = new ObservableCollection<Message>();
else Messages = messages;
}
public SocketIOSocket SocketIOSocket { get => socketIOSocket; set => socketIOSocket = value; }
public void AddMessage(ChatMessage message)
public void AddMessage(Message message)
{
Messages.Add(message);
}

View File

@@ -1,16 +1,8 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SocketIOSharp.Common;
using SocketIOSharp.Server;
using SocketIOSharp.Client;
using SocketIOSharp.Server.Client;
using EngineIOSharp.Common.Enum;
using Json.Net;
using System.Net;
using SocketIOSharp.Common.Packet;
using System.Threading;
using PolyChat.Models.Exceptions;
@@ -18,14 +10,22 @@ namespace PolyChat.Models
{
class Client
{
private SocketIOClient connection;
private SocketIOClient connection_client = null;
private SocketIOSocket connection_server = null;
private Boolean connected = false;
private String ipSelf;
public Client(SocketIOClient connection, String ip)
{
this.ipSelf = ip;
this.connection = connection;
this.connection_client = connection;
InitEventHandlers(this, connection);
}
public Client(SocketIOSocket connection, String ip)
{
this.ipSelf = ip;
this.connection_server = connection;
InitEventHandlers(this, connection);
}
@@ -45,7 +45,7 @@ namespace PolyChat.Models
new Thread(() =>
{
//create msg
ChatMessage msg = new ChatMessage(chatMessage, false, Controller.ip);
Message msg = new Message(chatMessage, false, Controller.ip);
//convert msg
String petJson = JsonNet.Serialize(msg);
@@ -62,7 +62,13 @@ namespace PolyChat.Models
throw new MessageTimedOutException(i*sleeptimer);
}
}
connection.Emit(code.ToString(), petJson);
if (connection_client != null)
{
connection_client.Emit(code.ToString(), petJson);
}else if (connection_server != null)
{
connection_server.Emit(code.ToString(), petJson);
}
}).Start();
}
/*
@@ -77,13 +83,13 @@ namespace PolyChat.Models
new Thread(() =>
{
//create msg
ChatMessage msg = new ChatMessage( Controller.ip);
Message msg = new Message( Controller.ip);
//convert msg
String petJson = JsonNet.Serialize(msg);
//send msg
connection.Emit(code.ToString(), petJson);
connection_client.Emit(code.ToString(), petJson);
}).Start();
}
*/
@@ -93,7 +99,7 @@ namespace PolyChat.Models
//===================================================================================
/// <summary>
/// handles all events of client server communiation
/// handles all events of client to server communiation
/// </summary>
/// <param name="client">self</param>
/// <param name="connection"></param>
@@ -101,10 +107,9 @@ namespace PolyChat.Models
{
connection.On(SendCode.Message.ToString(), (Data) =>
{
ChatMessage pet = JsonNet.Deserialize<ChatMessage>(BitConverter.ToString(Data[0].ToObject<byte[]>()));
Message pet = new Message(Data[0]);
//TODO: send message to GUI
});
connection.On(SendCode.Command.ToString(), (Data) =>
{
Console.WriteLine("Command recieved!" + Data[0]);
@@ -115,6 +120,27 @@ namespace PolyChat.Models
client.connected = true;
});
}
/// <summary>
/// handles all events of server to client communiation
/// </summary>
/// <param name="client">self</param>
/// <param name="connection"></param>
private static void InitEventHandlers(Client client, SocketIOSocket connection)
{
connection.On(SendCode.Message.ToString(), (Data) =>
{
Message pet = new Message(Data[0]);
//TODO: send message to GUI
});
connection.On(SendCode.Command.ToString(), (Data) =>
{
Console.WriteLine("Command recieved!" + Data[0]);
});
client.connected = true;
}
//==================================================================================
//Getter and Setter
//==================================================================================

View File

@@ -0,0 +1,55 @@
using Newtonsoft.Json.Linq;
using System;
namespace PolyChat.Models
{
public class Message
{
public readonly string Sender;
public readonly DateTime Timestamp = new DateTime(1970, 01, 01);
public readonly string Msg = "empty";
public readonly string Ip;
public readonly bool Foreign;
public readonly string StringTimeStamp;
/// <summary>
/// create new Message object from parameters
/// </summary>
/// <param name="Msg"></param>
/// <param name="Foreign"></param>
/// <param name="Sender"></param>
/// <param name="Ip"></param>
public Message(string Msg = "", bool Foreign = true, string Sender= "Unknown", string Ip = "127.0.0.1")
{
this.Sender = Sender;
this.Timestamp = DateTime.Now;
StringTimeStamp = Timestamp.ToString();
this.Msg = Msg;
this.Foreign = Foreign;
this.Ip = Ip;
}
/// <summary>
/// create new Message object from JToken (json)
/// </summary>
/// <param name="data"></param>
public Message(JToken data)
{
Message m = (Message) data[0].ToObject<Message>();
Sender = m.Sender;
Timestamp = m.Timestamp;
StringTimeStamp = Timestamp.ToString();
Msg = m.Msg;
Ip = m.Ip;
Foreign = m.Foreign;
}
override
public string ToString()
{
string prefix = Foreign ? "Other" : "Me";
return $"{prefix}: {Msg}({Sender})";
}
}
}

View File

@@ -1,10 +1,16 @@
using System;
using System.Diagnostics;
using System.Collections.Generic;
using SocketIOSharp.Client;
using EngineIOSharp.Common.Enum;
using System.Net;
using PolyChat.Models.Exceptions;
//dependencies for server functionality
using SocketIOSharp.Server;
using SocketIOSharp.Server.Client;
using Newtonsoft.Json.Linq;
namespace PolyChat.Models
{
class NetworkingController
@@ -12,12 +18,19 @@ namespace PolyChat.Models
public List<Client> clients = new List<Client>();
private String ownName = "";
private IPAddress ownIP;
MainPage uiController;
private readonly ushort Port;
private SocketIOServer Server;
private readonly MainPage uiController;
public NetworkingController (MainPage uiController)
public NetworkingController (MainPage uiController, ushort Port = 8050)
{
this.uiController = uiController;
this.ownIP = getIP();
this.Port = Port;
ownIP = getIP();
Server = new SocketIOServer(new SocketIOServerOption(Port));
Server.OnConnection((socket) => connectNewClient(socket));
Server.Start();
Debug.WriteLine($"Server started, binding to port {Port}, waiting for connection...");
}
//EXTERNAL METHODS
@@ -33,7 +46,20 @@ namespace PolyChat.Models
connection.Connect();
clients.Add(new Client(connection, ip));
}
/// <summary>
/// handle incomming connection
/// </summary>
/// <param name="ip"> server to connect to </param>
private void connectNewClient(SocketIOSocket socket)
{
socket.On(SendCode.Initial.ToString(), (JToken[] Data) =>
{
Message m = new Message(Data[0]);
clients.Add(new Client(socket,m.Ip));
});
}
/// <summary>
/// sends Message to given ip
/// </summary>
@@ -83,7 +109,7 @@ namespace PolyChat.Models
//=========================================================================================================================================================================================
/// <summary>
/// returns client that fits to ip adress
/// returns client that fit to ip address
/// </summary>
/// <param name="ip"></param>
/// <returns></returns>

View File

@@ -1,53 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Json.Net;
using SocketIOSharp.Common;
using SocketIOSharp.Server;
using SocketIOSharp.Server.Client;
namespace PolyChat.Models
{
class Socket
{
private Controller p;
private readonly ushort Port;
private SocketIOServer server;
private List<SocketIOSocket> Sockets = new List<SocketIOSocket>();
/// <summary>
/// creates server on specified port
/// </summary>
/// <param name="Port"></param>
public Socket(Controller p, ushort Port = 8050)
{
this.Port = Port;
this.p = p;
server = new SocketIOServer(new SocketIOServerOption(Port));
server.OnConnection((socket) => OnConnect(socket));
server.Start();
Console.WriteLine($"Server started, binding to port {Port}, waiting for connection...");
}
private void OnConnect(SocketIOSocket socket)
{
Console.WriteLine($"{socket.GetHashCode()} connected to the server");
Sockets.Add(socket);
socket.On(SocketIOEvent.DISCONNECT, () => OnDisconnect(socket));
socket.On("Message", (Data) => p.OnMessageCallback(socket, Data));
}
private void OnDisconnect(SocketIOSocket socket)
{
Sockets.Remove(socket);
}
public bool SendMessage(SocketIOSocket socket)
{
return false;
}
}
}

View File

@@ -122,7 +122,7 @@
<Compile Include="MainPage.xaml.cs">
<DependentUpon>MainPage.xaml</DependentUpon>
</Compile>
<Compile Include="Models\ChatMessage.cs" />
<Compile Include="Models\Message.cs" />
<Compile Include="Models\ChatPartner.cs" />
<Compile Include="Models\Exceptions\MessageTimedOutException.cs" />
<Compile Include="Models\NetworkingController.cs" />
@@ -130,7 +130,6 @@
<Compile Include="Models\ClientHandler.cs" />
<Compile Include="Models\Exceptions\ConnectionFailedException.cs" />
<Compile Include="Models\SendCode.cs" />
<Compile Include="Models\Socket.cs" />
<Compile Include="Controller.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Util\IP.cs" />