Skip to content

Commit

Permalink
Added client disconnection detection & Refactoring.
Browse files Browse the repository at this point in the history
  • Loading branch information
Ambratolm authored and Ambratolm committed Jul 14, 2021
1 parent 8682860 commit 9bb8878
Show file tree
Hide file tree
Showing 17 changed files with 268 additions and 143 deletions.
18 changes: 9 additions & 9 deletions Chat Starter Client/Form_Client.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

45 changes: 26 additions & 19 deletions Chat Starter Client/Form_Client.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Threading;
using System.Windows.Forms;
using ChatStarterCommon;
using System.Threading.Tasks;

namespace ChatStarterClient
{
Expand All @@ -11,14 +12,17 @@ enum Status { Initial, Sending }
private ChatClient _chatClient;
private string _userName;

public Form_Client(ChatClient chatClient, string userName)
public Form_Client()
{
InitializeComponent();
_chatClient = chatClient;
_userName = userName;
DisplayClientInfos();
SetStatus(Status.Initial);
ReceiveAsync();
if (Form_Connection.ShowAndTryGetInput(out _chatClient, out _userName, this))
{
SetStatus(Status.Initial);
DisplayClientInfos();
ReceiveTextAsync();
return;
}
Load += (s, e) => Close();
}

#region Common Methods
Expand All @@ -41,35 +45,38 @@ private void SetStatus(Status status)
}
}

private void ReceiveAsync()
private void ReceiveTextAsync()
{
new Thread(() =>
Task.Factory.StartNew(() =>
{
while (true)
try
{
try
while (true)
{
string message = _chatClient.ReceiveText();
Invoke((MethodInvoker)delegate()
{
Log(message);
});
}
catch
{
break;
}
}
Invoke((MethodInvoker)delegate()
catch (Exception exception)
{
Owner.Show();
Close();
});
}).Start();
Invoke((MethodInvoker)delegate()
{
MessageBox.Show(exception.Message, Application.ProductName,
MessageBoxButtons.OK, MessageBoxIcon.Error);
_chatClient.Disconnect(true);
if (Owner != null) Owner.Show();
Close();
});
}
});
}

private void Log(string message)
{
textBox_log.AppendText(string.Format("[{0}] ", DateTime.Now.ToString("HH:mm:ss")));
textBox_log.AppendText(message);
textBox_log.AppendText(Environment.NewLine);
}
Expand Down
18 changes: 18 additions & 0 deletions Chat Starter Client/Form_Client.resx
Original file line number Diff line number Diff line change
Expand Up @@ -117,9 +117,27 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="textBox_message.Locked" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="textBox_log.Locked" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="statusStrip_main.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="statusStrip_main.Locked" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="button_send.Locked" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="$this.Locked" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>64</value>
</metadata>
<assembly alias="System.Drawing" name="System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<data name="$this.Icon" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>
Expand Down
81 changes: 50 additions & 31 deletions Chat Starter Client/Form_Connection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ private enum Status { Initial, Connecting }
private int _originalHeight;
private bool _advancedSettingsVisible;

public string UserName { get; private set; }
public ChatClient ChatClient { get; private set; }

public Form_Connection()
{
InitializeComponent();
Expand All @@ -23,6 +26,21 @@ public Form_Connection()
HideAdvancedSettings();
}

public static bool ShowAndTryGetInput(out ChatClient chatClient, out string userName,
IWin32Window owner = null)
{
Form_Connection form_connection = new Form_Connection();
if (form_connection.ShowDialog(owner) == DialogResult.OK)
{
chatClient = form_connection.ChatClient;
userName = form_connection.UserName;
return true;
}
chatClient = null;
userName = null;
return false;
}

#region Common Methods
private void SetStatus(Status status)
{
Expand All @@ -48,6 +66,34 @@ private void SetStatus(Status status)
}
}

private void ConnectAsync(IPAddress localIPAddress, int localPort,
IPAddress remoteIPAddress, int remotePort)
{
Task.Factory.StartNew(() =>
{
try
{
ChatClient = new ChatClient(localIPAddress, localPort);
ChatClient.Connect(remoteIPAddress, remotePort);
ChatClient.SendText(textBox_userName.Text);
Invoke((MethodInvoker)delegate()
{
DialogResult = DialogResult.OK;
Close();
});
}
catch (Exception exception)
{
Invoke((MethodInvoker)delegate()
{
MessageBox.Show(exception.Message, Application.ProductName,
MessageBoxButtons.OK, MessageBoxIcon.Error);
SetStatus(Status.Initial);
});
}
});
}

private void SetError(Control control = null, string text = null)
{
if (control == null && text == null)
Expand Down Expand Up @@ -130,6 +176,9 @@ private void button_connect_Click(object sender, EventArgs e)
textBox_userName.SelectAll();
inputHasErrors = true;
}

UserName = textBox_userName.Text;

if (!Network.TryParseIPAddress(textBox_localIPAddress.Text, out localIPAddress))
{
SetError(label_localIPAddress, "Invalid IP Address");
Expand Down Expand Up @@ -164,37 +213,7 @@ private void button_connect_Click(object sender, EventArgs e)
}

SetStatus(Status.Connecting);
Task<ChatClient> connectionTask = Task.Factory.StartNew<ChatClient>(() =>
{
ChatClient chatClient = new ChatClient(localIPAddress, localPort);
chatClient.Connect(remoteIPAddress, remotePort);
chatClient.SendText(textBox_userName.Text);
return chatClient;
});

connectionTask.ContinueWith(task =>
{
if (task.Status == TaskStatus.RanToCompletion)
{
ChatClient chatClient = task.Result;
Invoke((MethodInvoker)delegate()
{
Hide();
SetStatus(Status.Initial);
new Form_Client(chatClient, textBox_userName.Text).Show(this);
});
}
else
{
Exception exception = task.Exception.GetBaseException();
Invoke((MethodInvoker)delegate()
{
MessageBox.Show(exception.Message, Application.ProductName,
MessageBoxButtons.OK, MessageBoxIcon.Error);
SetStatus(Status.Initial);
});
}
});
ConnectAsync(localIPAddress, localPort, remoteIPAddress, remotePort);
}

private void label_localIPAddress_Click(object sender, EventArgs e)
Expand Down
5 changes: 4 additions & 1 deletion Chat Starter Client/Form_Connection.resx
Original file line number Diff line number Diff line change
Expand Up @@ -160,11 +160,14 @@
<value>True</value>
</metadata>
<metadata name="errorProvider_main.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
<value>15, 10</value>
</metadata>
<metadata name="$this.Locked" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>54</value>
</metadata>
<assembly alias="System.Drawing" name="System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<data name="$this.Icon" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>
Expand Down
2 changes: 1 addition & 1 deletion Chat Starter Client/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form_Connection());
Application.Run(new Form_Client());
}
}
}
Binary file modified Chat Starter Client/bin/Release/Chat Starter Client.exe
Binary file not shown.
Binary file modified Chat Starter Client/bin/Release/Chat Starter Common.dll
Binary file not shown.
37 changes: 25 additions & 12 deletions Chat Starter Common/ChatClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ namespace ChatStarterCommon
{
public class ChatClient : IDisposable
{
private readonly Socket _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
private readonly Socket _socket;

public IPEndPoint LocalEndPoint
{
Expand All @@ -22,21 +22,23 @@ public IPEndPoint RemoteEndPoint
return (_socket.RemoteEndPoint as IPEndPoint);
}
}

public ChatClient(IPAddress localIPAddress, int localPort)
public bool IsConnected
{
if (!_socket.IsBound)
get
{
_socket.Bind(new IPEndPoint(localIPAddress, localPort));
return _socket.GetIsConnected();
}
}

public ChatClient(IPAddress localIPAddress, int localPort)
{
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_socket.Bind(new IPEndPoint(localIPAddress, localPort));
}

public void Connect(IPAddress remoteIPAddress, int remotePort)
{
if (!_socket.Connected)
{
_socket.Connect(new IPEndPoint(remoteIPAddress, remotePort));
}
_socket.Connect(new IPEndPoint(remoteIPAddress, remotePort));
}

public void SendText(string text)
Expand All @@ -49,8 +51,13 @@ public string ReceiveText()
return _socket.ReceiveString();
}

public void Stop()
public void Disconnect(bool close = false)
{
if (close)
{
Dispose();
return;
}
if (_socket.GetIsConnected())
{
_socket.Shutdown(SocketShutdown.Both);
Expand All @@ -60,9 +67,15 @@ public void Stop()

public void Dispose()
{
if (_socket != null)
Dispose(true);
GC.SuppressFinalize(this);
}

protected virtual void Dispose(bool disposing)
{
if (disposing)
{
_socket.Dispose();
_socket.Close();
}
}
}
Expand Down
Loading

0 comments on commit 9bb8878

Please sign in to comment.