I have created a application in WPF for LAN Chat. I have referenced this link:
http://www.geekpedia.com/tutorial239_Csharp-Chat-Part-1---Building-the-Chat-Client.html
and
http://www.geekpedia.com/tutorial239_Csharp-Chat-Part-2---Building-the-Chat-Client.html
The program compiles fine but I am facing some errors at runtime. Can any body help me? I am posting my WPF code here:
Server Chat:
XAML Code:
<pre lang="xml"><Window x:Class="chatclientwpf.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="597" Width="552">
<Grid>
<Label Height="27" Name="label1" VerticalAlignment="Top" HorizontalAlignment="Left" Width="60">Server IP:</Label>
<TextBox Height="23" Margin="92,4,166,0" Name="txtIp" VerticalAlignment="Top">192.168.1.3</TextBox>
<Label Height="28" HorizontalAlignment="Left" Margin="0,51,0,0" Name="label2" VerticalAlignment="Top" Width="70">User Name:</Label>
<TextBox Height="23" Margin="92,51,166,0" Name="txtUser" VerticalAlignment="Top">Aditya</TextBox>
<Button Height="23" HorizontalAlignment="Right" Margin="0,51.138,70,0" Name="btnConnect" VerticalAlignment="Top" Width="75" Click="btnConnect_Click">Connect</Button>
<TextBox Margin="27,99,59,178" Name="txtLog" IsEnabled="False" VerticalScrollBarVisibility="Visible" />
<TextBox Height="57" Margin="27,0,144,79" Name="txtMessage" VerticalAlignment="Bottom" VerticalScrollBarVisibility="Auto"/>
<Button Height="36" HorizontalAlignment="Right" Margin="0,0,59,90" Name="btnSend" VerticalAlignment="Bottom" Width="75" Click="btnSend_Click">Send</Button>
</Grid>
</Window>
C# coding:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace ChatServerWPF
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private delegate void UpdateStatusCallback(string strMessage);
private void btnListenbutton_Click(object sender, RoutedEventArgs e)
{
try
{
IPAddress ipAddr = IPAddress.Parse(txtIp.Text);
ChatServer mainServer = new ChatServer(ipAddr);
ChatServer.StatusChanged += new StatusChangedEventHandler(mainServer_StatusChanged);
mainServer.StartListening();
txtLog.AppendText("Monitoring for connections...\r\n");
}
catch (Exception ex)
{
MessageBox.Show("Error: "+ex);
}
}
public void mainServer_StatusChanged(object sender, StatusChangedEventArgs e)
{
this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new UpdateStatusCallback(this.UpdateStatus), new object[] { e.EventMessage });
}
private void UpdateStatus(string strMessage)
{
txtLog.AppendText(strMessage + "\r\n");
}
}
}
ChatServer.cs file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Collections;
namespace ChatServerWPF
{
public class StatusChangedEventArgs : EventArgs
{
private string EventMsg;
public string EventMessage
{
get
{
return EventMsg;
}
set
{
EventMsg = value;
}
}
public StatusChangedEventArgs(string strEventMsg)
{
EventMsg = strEventMsg;
}
}
public delegate void StatusChangedEventHandler(object sender, StatusChangedEventArgs e);
class ChatServer
{
public static Hashtable htUsers = new Hashtable(30);
public static Hashtable htConnections = new Hashtable(30);
private IPAddress ipAddress;
private TcpClient tcpClient;
public static event StatusChangedEventHandler StatusChanged;
private static StatusChangedEventArgs e;
public ChatServer(IPAddress address)
{
ipAddress = address;
}
private Thread thrListener;
private TcpListener tlsClient;
bool ServRunning = false;
public static void AddUser(TcpClient tcpUser, string strUsername)
{
ChatServer.htUsers.Add(strUsername, tcpUser);
ChatServer.htConnections.Add(tcpUser, strUsername);
SendAdminMessage(htConnections[tcpUser] + " has joined us");
}
public static void RemoveUser(TcpClient tcpUser)
{
if (htConnections[tcpUser] != null)
{
SendAdminMessage(htConnections[tcpUser] + " has left us");
ChatServer.htUsers.Remove(ChatServer.htConnections[tcpUser]);
ChatServer.htConnections.Remove(tcpUser);
}
}
public static void OnStatusChanged(StatusChangedEventArgs e)
{
StatusChangedEventHandler statusHandler = StatusChanged;
if (statusHandler != null)
{
statusHandler(null, e);
}
}
public static void SendAdminMessage(string Message)
{
StreamWriter swSenderSender;
e = new StatusChangedEventArgs("Administrator: " + Message);
OnStatusChanged(e);
TcpClient[] tcpClients = new TcpClient[ChatServer.htUsers.Count];
ChatServer.htUsers.Values.CopyTo(tcpClients, 0);
for (int i = 0; i < tcpClients.Length; i++)
{
try
{
if (Message.Trim() == "" || tcpClients[i] == null)
{
continue;
}
swSenderSender = new StreamWriter(tcpClients[i].GetStream());
swSenderSender.WriteLine("Administrator: " + Message);
swSenderSender.Flush();
swSenderSender = null;
}
catch
{
RemoveUser(tcpClients[i]);
}
}
}
public static void SendMessage(string From, string Message)
{
StreamWriter swSenderSender;
e = new StatusChangedEventArgs(From + " says: " + Message);
OnStatusChanged(e);
TcpClient[] tcpClients = new TcpClient[ChatServer.htUsers.Count];
ChatServer.htUsers.Values.CopyTo(tcpClients, 0);
for (int i = 0; i < tcpClients.Length; i++)
{
try
{
if (Message.Trim() == "" || tcpClients[i] == null)
{
continue;
}
swSenderSender = new StreamWriter(tcpClients[i].GetStream());
swSenderSender.WriteLine(From + " says: " + Message);
swSenderSender.Flush();
swSenderSender = null;
}
catch
{
RemoveUser(tcpClients[i]);
}
}
}
public void StartListening()
{
IPAddress ipaLocal = ipAddress;
tlsClient = new TcpListener(1986);
tlsClient.Start();
ServRunning = true;
thrListener = new Thread(KeepListening);
thrListener.Start();
}
private void KeepListening()
{
while (ServRunning == true)
{
tcpClient = tlsClient.AcceptTcpClient();
Connection newConnection = new Connection(tcpClient); newConnection = new Connection(tcpClient);
}
}
}
class Connection
{
TcpClient tcpClient;
private Thread thrSender;
private StreamReader srReceiver;
private StreamWriter swSender;
private string currUser;
private string strResponse;
public Connection(TcpClient tcpCon)
{
tcpClient = tcpCon;
thrSender = new Thread(AcceptClient);
thrSender.Start();
}
private void CloseConnection()
{
tcpClient.Close();
srReceiver.Close();
swSender.Close();
}
private void AcceptClient()
{
srReceiver = new System.IO.StreamReader(tcpClient.GetStream());
swSender = new System.IO.StreamWriter(tcpClient.GetStream());
currUser = srReceiver.ReadLine();
if (currUser != "")
{
if (ChatServer.htUsers.Contains(currUser) == true)
{
swSender.WriteLine("0|This username already exists.");
swSender.Flush();
CloseConnection();
return;
}
else if (currUser == "Administrator")
{
swSender.WriteLine("0|This username is reserved.");
swSender.Flush();
CloseConnection();
return;
}
else
{
swSender.WriteLine("1");
swSender.Flush();
ChatServer.AddUser(tcpClient, currUser);
}
}
else
{
CloseConnection();
return;
}
try
{
while ((strResponse = srReceiver.ReadLine()) != "")
{
if (strResponse == null)
{
ChatServer.RemoveUser(tcpClient);
}
else
{
ChatServer.SendMessage(currUser, strResponse);
}
}
}
catch
{
ChatServer.RemoveUser(tcpClient);
}
}
}
}
Now this is all about Server chat.. Now I will give Client chat:
XAML Code:
<pre lang="xml"><Window x:Class="chatclientwpf.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="597" Width="552">
<Grid>
<Label Height="27" Name="label1" VerticalAlignment="Top" HorizontalAlignment="Left" Width="60">Server IP:</Label>
<TextBox Height="23" Margin="92,4,166,0" Name="txtIp" VerticalAlignment="Top">192.168.1.3</TextBox>
<Label Height="28" HorizontalAlignment="Left" Margin="0,51,0,0" Name="label2" VerticalAlignment="Top" Width="70">User Name:</Label>
<TextBox Height="23" Margin="92,51,166,0" Name="txtUser" VerticalAlignment="Top">Aditya</TextBox>
<Button Height="23" HorizontalAlignment="Right" Margin="0,51.138,70,0" Name="btnConnect" VerticalAlignment="Top" Width="75" Click="btnConnect_Click">Connect</Button>
<TextBox Margin="27,99,59,178" Name="txtLog" IsEnabled="False" VerticalScrollBarVisibility="Visible" />
<TextBox Height="57" Margin="27,0,144,79" Name="txtMessage" VerticalAlignment="Bottom" VerticalScrollBarVisibility="Auto"/>
<Button Height="36" HorizontalAlignment="Right" Margin="0,0,59,90" Name="btnSend" VerticalAlignment="Bottom" Width="75" Click="btnSend_Click">Send</Button>
</Grid>
</Window
>
C# coding:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
namespace chatclientwpf
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private string UserName = "Unknown";
private StreamWriter swSender;
private StreamReader srReceiver;
private TcpClient tcpServer;
private delegate void UpdateLogCallback(string strMessage);
private delegate void CloseConnectionCallback(string strReason);
private Thread thrMessaging;
private IPAddress ipAddr;
private bool Connected;
private void btnConnect_Click(object sender, RoutedEventArgs e)
{
try
{
if (Connected == false)
{
InitializeConnection();
}
else
{
CloseConnection("Disconnected at user's request.");
}
}
catch (Exception ex)
{
MessageBox.Show("Error :"+ex);
}
}
private void InitializeConnection()
{
try
{
ipAddr = IPAddress.Parse(txtIp.Text);
tcpServer = new TcpClient();
tcpServer.Connect(ipAddr, 1986);
Connected = true;
UserName = txtUser.Text;
txtIp.IsEnabled = false;
txtUser.IsEnabled = false;
txtMessage.IsEnabled = true;
btnSend.IsEnabled = true;
btnConnect.Content = "Disconnect";
swSender = new StreamWriter(tcpServer.GetStream());
swSender.WriteLine(txtUser.Text);
swSender.Flush();
thrMessaging = new Thread(new ThreadStart(ReceiveMessages));
thrMessaging.Start();
}
catch (Exception ex)
{
MessageBox.Show("Error :"+ex);
}
}
private void UpdateLog(string strMessage)
{
txtLog.AppendText(strMessage + "\r\n");
}
private void btnSend_Click(object sender, RoutedEventArgs e)
{
SendMessage();
}
private void txtMessage_KeyDown(object sender, KeyEventArgs e )
{
if (e.Key == Key.Enter)
{
SendMessage();
}
}
private void SendMessage()
{
if (txtMessage.LineCount >= 1)
{
swSender.WriteLine(txtMessage.Text);
swSender.Flush();
}
txtMessage.Text = "";
}
private void CloseConnection(string Reason)
{
try
{
txtLog.AppendText(Reason + "\r\n");
txtIp.IsEnabled = true;
txtUser.IsEnabled = true;
txtMessage.IsEnabled = false;
btnSend.IsEnabled = false;
btnConnect.Content = "Connect";
Connected = false;
swSender.Close();
srReceiver.Close();
tcpServer.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error :"+ex);
}
}
public void OnApplicationExit(object sender, EventArgs e)
{
if (Connected == true)
{
Connected = false;
swSender.Close();
srReceiver.Close();
tcpServer.Close();
}
}
private void ReceiveMessages()
{
srReceiver = new StreamReader(tcpServer.GetStream());
string ConResponse = srReceiver.ReadLine();
if (ConResponse[0] == '1')
{
this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,new UpdateLogCallback(this.UpdateLog), new object[] { "Connected Successfully!" });
}
else
{
string Reason = "Not Connected: ";
Reason += ConResponse.Substring(2, ConResponse.Length - 2);
this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new CloseConnectionCallback(this.CloseConnection), new object[] { Reason });
return;
}
while (Connected)
{
this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new UpdateLogCallback(this.UpdateLog), new object[] { srReceiver.ReadLine() });
}
}
}
}
I am getting error at Invoke method. Please study this code and suggest me changes where ever necessary..
Thanks.