remove Socket.cs, integrate Socket.cs into Networkcontroller.cs

This commit is contained in:
Felix Hartmann (PEA3-Fe-FI)
2021-09-21 12:32:35 +02:00
parent 4948d32a58
commit a2c35a7536
9 changed files with 145 additions and 114 deletions

View File

@@ -13,7 +13,7 @@ namespace PolyChat
public class Controller public class Controller
{ {
public static string ip; public static string ip;
private MainPage UIController; private readonly MainPage UIController;
private ClientHandler clientHandler; private ClientHandler clientHandler;
/* /*
@@ -31,7 +31,7 @@ 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, msg, DateTime.Now); clientHandler.getClient(ip).send Message(SendCode.Message, msg, DateTime.Now);
} }
*/ */
/// <summary> /// <summary>
@@ -61,7 +61,6 @@ namespace PolyChat
break; break;
} }
} }
Socket s = new Socket(this);
} }
else if (input.Equals("client")) 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() static string[] GetIPs()
{ {
IPHostEntry ipEntry = Dns.GetHostEntry(Dns.GetHostName()); IPHostEntry ipEntry = Dns.GetHostEntry(Dns.GetHostName());
IPAddress[] addr = ipEntry.AddressList; IPAddress[] addr = ipEntry.AddressList;
string[] ips = new string[addr.Length]; 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(); ips[i] = addr.ToString();
} }

View File

@@ -96,9 +96,9 @@
<ScrollViewer Grid.Row="1" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Hidden"> <ScrollViewer Grid.Row="1" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Hidden">
<ListView x:Name="listViewMessages" VerticalAlignment="Bottom" Margin="4 16"> <ListView x:Name="listViewMessages" VerticalAlignment="Bottom" Margin="4 16">
<ListView.ItemTemplate> <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}"> <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 Timestamp.ToShortDateString()}"/>
<TextBlock Text="{x:Bind Foreign}"/> <TextBlock Text="{x:Bind Foreign}"/>
</StackPanel> </StackPanel>

View File

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

View File

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

View File

@@ -1,16 +1,8 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SocketIOSharp.Common; using SocketIOSharp.Common;
using SocketIOSharp.Server;
using SocketIOSharp.Client; using SocketIOSharp.Client;
using SocketIOSharp.Server.Client; using SocketIOSharp.Server.Client;
using EngineIOSharp.Common.Enum;
using Json.Net; using Json.Net;
using System.Net;
using SocketIOSharp.Common.Packet;
using System.Threading; using System.Threading;
using PolyChat.Models.Exceptions; using PolyChat.Models.Exceptions;
@@ -18,14 +10,22 @@ namespace PolyChat.Models
{ {
class Client class Client
{ {
private SocketIOClient connection; private SocketIOClient connection_client = null;
private SocketIOSocket connection_server = null;
private Boolean connected = false; private Boolean connected = false;
private String ipSelf; private String ipSelf;
public Client(SocketIOClient connection, String ip) public Client(SocketIOClient connection, String ip)
{ {
this.ipSelf = 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); InitEventHandlers(this, connection);
} }
@@ -45,7 +45,7 @@ namespace PolyChat.Models
new Thread(() => new Thread(() =>
{ {
//create msg //create msg
ChatMessage msg = new ChatMessage(chatMessage, false, Controller.ip); Message msg = new Message(chatMessage, false, Controller.ip);
//convert msg //convert msg
String petJson = JsonNet.Serialize(msg); String petJson = JsonNet.Serialize(msg);
@@ -62,7 +62,13 @@ namespace PolyChat.Models
throw new MessageTimedOutException(i*sleeptimer); 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(); }).Start();
} }
/* /*
@@ -77,13 +83,13 @@ namespace PolyChat.Models
new Thread(() => new Thread(() =>
{ {
//create msg //create msg
ChatMessage msg = new ChatMessage( Controller.ip); Message msg = new Message( Controller.ip);
//convert msg //convert msg
String petJson = JsonNet.Serialize(msg); String petJson = JsonNet.Serialize(msg);
//send msg //send msg
connection.Emit(code.ToString(), petJson); connection_client.Emit(code.ToString(), petJson);
}).Start(); }).Start();
} }
*/ */
@@ -93,7 +99,7 @@ namespace PolyChat.Models
//=================================================================================== //===================================================================================
/// <summary> /// <summary>
/// handles all events of client server communiation /// handles all events of client to server communiation
/// </summary> /// </summary>
/// <param name="client">self</param> /// <param name="client">self</param>
/// <param name="connection"></param> /// <param name="connection"></param>
@@ -101,7 +107,30 @@ namespace PolyChat.Models
{ {
connection.On(SendCode.Message.ToString(), (Data) => 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]);
});
connection.On(SocketIOEvent.CONNECTION, () =>
{
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 //TODO: send message to GUI
}); });

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;
using System.Diagnostics;
using System.Collections.Generic; using System.Collections.Generic;
using SocketIOSharp.Client; using SocketIOSharp.Client;
using EngineIOSharp.Common.Enum; using EngineIOSharp.Common.Enum;
using System.Net; using System.Net;
using PolyChat.Models.Exceptions; using PolyChat.Models.Exceptions;
//dependencies for server functionality
using SocketIOSharp.Server;
using SocketIOSharp.Server.Client;
using Newtonsoft.Json.Linq;
namespace PolyChat.Models namespace PolyChat.Models
{ {
class NetworkingController class NetworkingController
@@ -12,12 +18,19 @@ namespace PolyChat.Models
public List<Client> clients = new List<Client>(); public List<Client> clients = new List<Client>();
private String ownName = ""; private String ownName = "";
private IPAddress ownIP; 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.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 //EXTERNAL METHODS
@@ -33,7 +46,20 @@ namespace PolyChat.Models
connection.Connect(); connection.Connect();
clients.Add(new Client(connection, ip)); 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> /// <summary>
/// sends Message to given ip /// sends Message to given ip
/// </summary> /// </summary>
@@ -83,7 +109,7 @@ namespace PolyChat.Models
//========================================================================================================================================================================================= //=========================================================================================================================================================================================
/// <summary> /// <summary>
/// returns client that fits to ip adress /// returns client that fit to ip address
/// </summary> /// </summary>
/// <param name="ip"></param> /// <param name="ip"></param>
/// <returns></returns> /// <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"> <Compile Include="MainPage.xaml.cs">
<DependentUpon>MainPage.xaml</DependentUpon> <DependentUpon>MainPage.xaml</DependentUpon>
</Compile> </Compile>
<Compile Include="Models\ChatMessage.cs" /> <Compile Include="Models\Message.cs" />
<Compile Include="Models\ChatPartner.cs" /> <Compile Include="Models\ChatPartner.cs" />
<Compile Include="Models\Exceptions\MessageTimedOutException.cs" /> <Compile Include="Models\Exceptions\MessageTimedOutException.cs" />
<Compile Include="Models\NetworkingController.cs" /> <Compile Include="Models\NetworkingController.cs" />
@@ -130,7 +130,6 @@
<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\SendCode.cs" /> <Compile Include="Models\SendCode.cs" />
<Compile Include="Models\Socket.cs" />
<Compile Include="Controller.cs" /> <Compile Include="Controller.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Util\IP.cs" /> <Compile Include="Util\IP.cs" />