Posts Tagged ‘IP address’

java-ip-to-decimal
In this tutorial, we show you how to convert an IP address to its decimal equivalent in Java, and vice versa.

For examples :

255.255.255.255  <->  4294967295
192.168.1.2      <->  3232235778

1. IP Address to Decimal

We show you two ways to convert an IP address to a decimal number

  1. Normal power of 256
  2. Bit shifting

Read more

 

Advertisements

Shiro Broadband Router

Step to Configure TP-Link Router
——————————————

1.Power on Router.
2.Connect your PC/laptop with Router via ethernet cable. [Use Routers LAN ports only not WAN]
3.Your PC automatically gets IP address as default DHCP is enabled on Router.
You get IP from 192.168.1.x or 192.168.0.x (x: 2-254)
Router default IP varies from model to model either 192.168.1.1 or 192.168.0.1(written on router box)
4.Open browser and enter router default IP address http://192.168.1.1 according to your router.
5.Router authentication required. By default username/password is admin/admin.
6.TP-Link console opens.
7.Click on Network > LAN, change IP address to 192.168.1.2. Its due to your Modem
default IP address is 192.168.1.1.
8. Its reboots automatically.
9. Now open TP-Link console with new IP address which is 192.168.1.2
10.Click on Wireless Settings, Change default SSID with your choice like “Johnny”
11.Change other setting as per requirment like country. Rest leave by default.
12.Click on Wireless Security for making your wireless network secure.
13.Use WPA-PSK (Wireless security protocol)
14.Select your desired Encription like AES or TKIP.
15.Enter PSK password.
16. Select DHCP link.
17. Disable it. (As your Modems DHCP is already on)
18. Click system Tools > Reboot.
19. Your Router is ready to use, now just plug the ethernet with modem.

Note:
The guide is written because the novice user always in confusion, how to configure router.
Almost all vendors Wireless Router can be configureable with this guide with some minor change.
The Guide is made while the configuration of TP-Link WR-642G.
The Basic concept is to change the Router IP address & disable Routers DHCP service.

AJAX

In the following example we will see how to display server IP address dynamically with the help of AJAX, HTML , & PHP.

SimpleAjax.html

<html>
<body>
// <![CDATA[
javascript” >
// ]]>
function ajaxfunction()
{
var xmlhttp;
if(window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject(“Microsoft.XMLHTTP”);
}
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
document.timeform.time.value=xmlhttp.responseText;
}
}
xmlhttp.open(“GET”,”SimpleAjax.php”,true);
xmlhttp.send(null);
}
</script>
<form name=”timeform” >
Name:<input type=”text” name=”Name” onkeyup=”ajaxfunction()”; />
<br/>
Time:<input type=”text” name=”time”/>
<!–form>
</body>
</html>

SimpleAjax.php

<?php
echo ($SERVER_ADDR);
?>

SimpleAjax.html

<html>
<body>
// <![CDATA[
javascript” >
// ]]>
function ajaxfunction()
{
var xmlhttp;
if(window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject(“Microsoft.XMLHTTP”);
}
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
document.timeform.time.value=xmlhttp.responseText;
}
}
xmlhttp.open(“GET”,”SimpleAjax.php”,true);
xmlhttp.send(null);
}
</script>
<form name=”timeform” >
Name:<input type=”text” name=”Name” onkeyup=”ajaxfunction()”; />
<br/>
Time:<input type=”text” name=”time”/>
</form>
</body>
</html>

Note: In this way we can get different dynamic values of server and other like time, date etc.

Image representing Google Search as depicted i...

Despite most operating systems nowadays have graphical user interface and most of the tools are implemented using one, the command line prompt (cmd) is still a powerful tool. This is especially true when it comes to performing administrative tasks or advanced networking information queries. In this article, we’ll show you how to find many network related information about a website using the command prompt. For examples, the article will be using the Google website.

Steps

  1. 1

    Start the command-line prompt. This is usually done by one of the following methods:

    • Going to Start >> All Programs >> Accessories >> Command Prompt on Windows Vista/7. According to your settings, in older systems (XP, 2000, etc), you might find “Accessories” directly on “Start”
    • Go to Start >> Run and then type cmd in the run dialog and press Enter.

IP Address and Connectivity

 

A screenshot of the ping command

 

  1. 1

    Type the following command to the command-line prompt, replacing google.com with the website you want to get the information for:

    • ping google.com
  2. 2

    Find the IP address of the website (more precisely, the server) on the first line, where it says “Pinging Website_Address_You_Entered [X.X.X.X] with 32 bytes of data:”

  3. 3

    Notice the connectivity between you machine and the server from the line where it says: “Packets: Sent = X, Received = X, Lost = X (X% loss),” where all the Xs will be replaced by numbers. This gives you an idea of how much percent of the packets sent to the server will be lost.

Routing Information

 

A screenshot of a tracert session

 

A screenshot of a pathping command execution

 

  1. 1

    Type the following command to the command-line prompt, replacing google.com with the website or server you want routing information for:

    • tracert google.com
  2. 2

    Notice the listing of hops along the route path of packets from your machine to the server. This gives you an idea of how many routers/hops the packet has to travel before reaching the server, starting from your machine.

  3. 3

    Use the pathping utility to find information about network latency and network loss at intermediate hops between a source and destination. Pathping sends multiple Echo Request messages to each router between a source and destination over a period of time and then computes results based on the packets returned from each router. Type the following to the command-line prompt:

    • pathping google.com

DNS information

 

A screenshot of nslookup execution

 

  1. 1

    Type the following on the command-line prompt, replacing google.com with the website or server you want DNS information for:

    • nslookup google.com
  2. 2

    Find the DNS server (first lines) and the IP addresses of the server you queried about.

Tips

  • Some of the commands explained above have other options that might be useful for finding out information about your internal network.
  • If you’re using these command in a corporate network or a school network, some of these commands might not give you results. Most institutions have firewalls with settings to deny services provided by these tools.

Download this Visual Studio 2005 project Download the Chat Server Application project (Visual Studio 2005)

This is the second part of a tutorial that teaches you how to create a C# chat application. In Part 1 – Building the Chat Clientwe’ve looked at how to create the chat application that connects to a chat server, and here we now look at how to build the chat server.

The Chat Server

The Chat Server application is a tad more complex than the Chat Client application because it needs to hold information on all the connected clients, await for messages from each and send incoming messages to all. I commented all the code so hopefully you won’t have any problems figuring it out without much commentary on the side from me.

Fire up a new instance of Visual Studio 2005 and in a new Windows Application project draw the following form:

Chat Server

The only controls we are interested in are the two TextBoxes (txtIp and txtLog) and the btnListen button. The IP address inside txtIp is the one where you want your chat server to be listening for incoming connections. You should use your local IP address, which if you’re not in a network it could be 192.168.0.1, but it’s best that you check using the ipconfig /all command in the MS-DOS Command Prompt window. The multi-line TextBox will hold information about connected clients and the messages that they are exchanging.

In the code view, start with the following using statements:

using System.Threading;

using System.Net;

using System.Net.Sockets;

using System.IO;

Move inside the class and declare a delagate which we will need in order to update the txtLog TextBox from another thread :

private delegate void UpdateStatusCallback(string strMessage);

Double-click the Start Listening button and you should arrive to it Click event. Have the event handler look like this:

private void btnListen_Click(object sender, EventArgs e)

{

// Parse the server’s IP address out of the TextBox

IPAddress ipAddr = IPAddress.Parse(txtIp.Text);

// Create a new instance of the ChatServer object

ChatServer mainServer = new ChatServer(ipAddr);

// Hook the StatusChanged event handler to mainServer_StatusChanged

ChatServer.StatusChanged += new StatusChangedEventHandler(mainServer_StatusChanged);

// Start listening for connections

mainServer.StartListening();

// Show that we started to listen for connections

txtLog.AppendText(“Monitoring for connections…\r\n”);

}

A couple of objects are being instantiated, including a ChatServer object. We will write the ChatServer class very soon, and you will see that it handles all the incoming connections. In turn, it will make use of another class that we will write, called Connection.
The next thing we do is to set up an event handler for the StatusChanged event, which is a custom event that we’re going to write very soon. It will inform us when a client has connected, a new message has been received, a client has disconnected, etc.
Finally the StartListening() method tells the ChatServer object to start listening for incoming connections.

Believe it or not, there are only a few more lines of code to go in this class. One of them is the event handler that we hooked earlier, and the other is the UpdateStatus() method that gets called when an update needs to be made to the form. It’s needed because we use Invoke() and the delegate we created earlier to make a cross-thread call (since the ChatServer will be working in a different thread):

public void mainServer_StatusChanged(object sender, StatusChangedEventArgs e)

{

// Call the method that updates the form

this.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { e.EventMessage });

}

private void UpdateStatus(string strMessage)

{

// Updates the log with the message

txtLog.AppendText(strMessage + “\r\n”);

}

And we’re done. Done with the Form1 class, of course. You should now create another file (I called mine ChatServer.cs) and inside it make sure you have all these using statements:

using System;

using System.Collections.Generic;

using System.Text;

using System.Net;

using System.Net.Sockets;

using System.IO;

using System.Threading;

using System.Collections;

We’ll need to use an event that notifies the form class when a new client has connected, disconnected, sent a message, etc. In order to create our own custom event, we need to first define its arguments. More exactly we want a string argument that tells us what type of event has occured (user has connected, user has disconnected, user x says y, etc..) If you’re not familiar with events and delegates you might want to read the Delegates and Events in C# tutorial from a week ago. Here is the class that gets and sets the event arguments:

// Holds the arguments for the StatusChanged event

public class StatusChangedEventArgs : EventArgs

{

// The argument we’re interested in is a message describing the event

private string EventMsg;

// Property for retrieving and setting the event message

public string EventMessage

{

get

{

return EventMsg;

}

set

{

EventMsg = value;

}

}

// Constructor for setting the event message

public StatusChangedEventArgs(string strEventMsg)

{

EventMsg = strEventMsg;

}

}

Moving on, outside this class we declare the actual delegate for the event handler:

// This delegate is needed to specify the parameters we’re passing with our event

public delegate void StatusChangedEventHandler(object sender, StatusChangedEventArgs e);

And now before we actually get to fire this event, we define the ChatServer class, in all its glory. Remember this is the class that we used back in Form1.cs:

class ChatServer

{

// This hash table stores users and connections (browsable by user)

public static Hashtable htUsers = new Hashtable(30); // 30 users at one time limit

// This hash table stores connections and users (browsable by connection)

public static Hashtable htConnections = new Hashtable(30); // 30 users at one time limit

// Will store the IP address passed to it

private IPAddress ipAddress;

private TcpClient tcpClient;

// The event and its argument will notify the form when a user has connected, disconnected, send message, etc.

public static event StatusChangedEventHandler StatusChanged;

private static StatusChangedEventArgs e;

// The constructor sets the IP address to the one retrieved by the instantiating object

public ChatServer(IPAddress address)

{

ipAddress = address;

}

// The thread that will hold the connection listener

private Thread thrListener;

// The TCP object that listens for connections

private TcpListener tlsClient;

// Will tell the while loop to keep monitoring for connections

bool ServRunning = false;

// Add the user to the hash tables

public static void AddUser(TcpClient tcpUser, string strUsername)

{

// First add the username and associated connection to both hash tables

ChatServer.htUsers.Add(strUsername, tcpUser);

ChatServer.htConnections.Add(tcpUser, strUsername);

// Tell of the new connection to all other users and to the server form

SendAdminMessage(htConnections[tcpUser] + ” has joined us”);

}

// Remove the user from the hash tables

public static void RemoveUser(TcpClient tcpUser)

{

// If the user is there

if (htConnections[tcpUser] != null)

{

// First show the information and tell the other users about the disconnection

SendAdminMessage(htConnections[tcpUser] + ” has left us”);

// Remove the user from the hash table

ChatServer.htUsers.Remove(ChatServer.htConnections[tcpUser]);

ChatServer.htConnections.Remove(tcpUser);

}

}

// This is called when we want to raise the StatusChanged event

public static void OnStatusChanged(StatusChangedEventArgs e)

{

StatusChangedEventHandler statusHandler = StatusChanged;

if (statusHandler != null)

{

// Invoke the delegate

statusHandler(null, e);

}

}

// Send administrative messages

public static void SendAdminMessage(string Message)

{

StreamWriter swSenderSender;

// First of all, show in our application who says what

e = new StatusChangedEventArgs(“Administrator: ” + Message);

OnStatusChanged(e);

// Create an array of TCP clients, the size of the number of users we have

TcpClient[] tcpClients = new TcpClient[ChatServer.htUsers.Count];

// Copy the TcpClient objects into the array

ChatServer.htUsers.Values.CopyTo(tcpClients, 0);

// Loop through the list of TCP clients

for (int i = 0; i < tcpClients.Length; i++)

{

// Try sending a message to each

try

{

// If the message is blank or the connection is null, break out

if (Message.Trim() == “” || tcpClients[i] == null)

{

continue;

}

// Send the message to the current user in the loop

swSenderSender = new StreamWriter(tcpClients[i].GetStream());

swSenderSender.WriteLine(“Administrator: ” + Message);

swSenderSender.Flush();

swSenderSender = null;

}

catch // If there was a problem, the user is not there anymore, remove him

{

RemoveUser(tcpClients[i]);

}

}

}

// Send messages from one user to all the others

public static void SendMessage(string From, string Message)

{

StreamWriter swSenderSender;

// First of all, show in our application who says what

e = new StatusChangedEventArgs(From + ” says: ” + Message);

OnStatusChanged(e);

// Create an array of TCP clients, the size of the number of users we have

TcpClient[] tcpClients = new TcpClient[ChatServer.htUsers.Count];

// Copy the TcpClient objects into the array

ChatServer.htUsers.Values.CopyTo(tcpClients, 0);

// Loop through the list of TCP clients

for (int i = 0; i < tcpClients.Length; i++)

{

// Try sending a message to each

try

{

// If the message is blank or the connection is null, break out

if (Message.Trim() == “” || tcpClients[i] == null)

{

continue;

}

// Send the message to the current user in the loop

swSenderSender = new StreamWriter(tcpClients[i].GetStream());

swSenderSender.WriteLine(From + ” says: ” + Message);

swSenderSender.Flush();

swSenderSender = null;

}

catch // If there was a problem, the user is not there anymore, remove him

{

RemoveUser(tcpClients[i]);

}

}

}

public void StartListening()

{

// Get the IP of the first network device, however this can prove unreliable on certain configurations

IPAddress ipaLocal = ipAddress;

// Create the TCP listener object using the IP of the server and the specified port

tlsClient = new TcpListener(1986);

// Start the TCP listener and listen for connections

tlsClient.Start();

// The while loop will check for true in this before checking for connections

ServRunning = true;

// Start the new tread that hosts the listener

thrListener = new Thread(KeepListening);

thrListener.Start();

}

private void KeepListening()

{

// While the server is running

while (ServRunning == true)

{

// Accept a pending connection

tcpClient = tlsClient.AcceptTcpClient();

// Create a new instance of Connection

Connection newConnection = new Connection(tcpClient);

}

}

}

Overwhelmed? It’s really not that complicated if you take it line by line and read the comments. It starts by defining two hash tables. These two hash tables will hold the username and the TCP connection associated with it. We need two of them because at one point we’ll want to retrieve the TCP connection by giving the username, and at some other point we’ll want to retrieve the username by giving the TCP connection. The 30 defines how many users the chat server can hold at one given point, but you can easily go into hundreds if needed, without worrying about a performance decrease.

The AddUser() method is obvious – it adds a new user to the hash tables, and thus to our list of connected chat clients. The RemoveUser() method does the opposite. The OnStatusChanged will fire the StatusChanged event, which is right now handled inside Form1.cs. Thus, it’s our way of updating the form with the latest message from inside this ChatServer object.

The SendAdminMessage sends an administrative message to all connected clients. You can see how it loops through the hash table and attempts to send them the message. If the message didn’t get through, they probably disconnected and we then remove them. This is very similar to what the SendMessage() method does, only that this time it sends a message from a specific chat client to all the others.

The StartListening() method is the one we called inside Form1, and it’s the fire starter, the instigator. It defines the first needed objects and starts a new thread that keeps listening for connections, and that is the KeepListening() method. And that’s where our story continues, because if you look inside the KeepListening() method you will see we create a new object of type Connection. That’s because each user connected to our server will have its own instance of Connection. If there are 10 users currently connected, there will be 10 instances of the Connection object. So let’s look at the final class of our chat server:

// This class handels connections; there will be as many instances of it as there will be connected users

class Connection

{

TcpClient tcpClient;

// The thread that will send information to the client

private Thread thrSender;

private StreamReader srReceiver;

private StreamWriter swSender;

private string currUser;

private string strResponse;

// The constructor of the class takes in a TCP connection

public Connection(TcpClient tcpCon)

{

tcpClient = tcpCon;

// The thread that accepts the client and awaits messages

thrSender = new Thread(AcceptClient);

// The thread calls the AcceptClient() method

thrSender.Start();

}

private void CloseConnection()

{

// Close the currently open objects

tcpClient.Close();

srReceiver.Close();

swSender.Close();

}

// Occures when a new client is accepted

private void AcceptClient()

{

srReceiver = new System.IO.StreamReader(tcpClient.GetStream());

swSender = new System.IO.StreamWriter(tcpClient.GetStream());

// Read the account information from the client

currUser = srReceiver.ReadLine();

// We got a response from the client

if (currUser != “”)

{

// Store the user name in the hash table

if (ChatServer.htUsers.Contains(currUser) == true)

{

// 0 means not connected

swSender.WriteLine(“0|This username already exists.”);

swSender.Flush();

CloseConnection();

return;

}

else if (currUser == “Administrator”)

{

// 0 means not connected

swSender.WriteLine(“0|This username is reserved.”);

swSender.Flush();

CloseConnection();

return;

}

else

{

// 1 means connected successfully

swSender.WriteLine(“1”);

swSender.Flush();

// Add the user to the hash tables and start listening for messages from him

ChatServer.AddUser(tcpClient, currUser);

}

}

else

{

CloseConnection();

return;

}

try

{

// Keep waiting for a message from the user

while ((strResponse = srReceiver.ReadLine()) != “”)

{

// If it’s invalid, remove the user

if (strResponse == null)

{

ChatServer.RemoveUser(tcpClient);

}

else

{

// Otherwise send the message to all the other users

ChatServer.SendMessage(currUser, strResponse);

}

}

}

catch

{

// If anything went wrong with this user, disconnect him

ChatServer.RemoveUser(tcpClient);

}

}

}

It doesn’t look too complicated, does it? There’s the constructor that initializes the TcpClient object, then there’s CloseConnection() which is called when we want to get rid of a currently connected client, and finally there’s AcceptClient() which checks for the username validity and if all is fine, it adds the user to the hash tables. If anything goes bad, it removes the user.

I’ll leave you chew on the code for a while now. It’s pretty much as easy as it can get for a C# based chat/server application, but that also means it can use more error handling. Also if you have any suggestions to improve the code or to fix a bug, feel free to post a comment below.

Chat Server Application

Download this Visual Studio 2005 project Download the Chat Client Application project(Visual Studio 2005)

Building a Chat Server and a Chat Client

To no avail I’ve been searching the web for a good C# chat client/server application that is not thousands of lines of code long. The only simple ones I could find were flawed or very buggy, but then again I tried to combine the good parts of all the tutorials I found into one application, and one tutorial that you can see here today. We are going to build a fairly larger application (a few hundred lines of codes) than the ones we’re used to here on Geekpedia, but we’re still going to keep it simple. In fact, there will be two applications: one is a chat server, that handles incoming connections, stores them in hash tables, and distributes new messages to everyone connected, and the other is of course, the chat client, which connects to the server, sends messages and listens for incoming messages. A little knowledge of C#’s networking objects, multi-threading, events and delegates will definitely help you understand this tutorial more easily. A good way to start learning about delegates, events and creating client-server applications is to read the Delegates and Events in C# tutorial first.
The chat server will be able to accept as many chat clients as allowed by the hash table (and you are able to define the limit of the hash table yourself), and it will also track all the messages that are going back and forth in its own chat window, so you should be able to scale this code to a full blown chat application as long as you add the necessary error handling and the bells and whistles.

 

The client application

The client application is, as you might have expected, the simpler one, since all it has to do is to attempt to connect to the chat server, request an username, start listening for messages and sending its own, and finally disconnecting.
Start Visual Studio 2005 and create a new C# Windows Application. I’ve given mine the obvious “Chat Client” name.

Chat Client Form

The first two TextBoxes (txtIp and txtUser) will hold the IP address of the server we want to connect to and the desired username. Before testing out this code keep in mind to change this IP address to the one of the computer in your network that runs the client. If you read the Delegates and Events in C# tutorial, you probably assume you can run the chat application and the server application on the same machine, without needing two different computers connected through a network or the Internet. And you would be right.
The Connect (btnConnect) and Send (btnSend) buttons are obvious, they’re for connecting to the server and sending messages. The large multi-line TextBox is named txtLog and it is where all the messages will be shown.The small TextBox at the bottom is called txtMessage and it is where the message to be sent to the server will be typed.

Now that we’re done with the actual design of the form, we can finally code. Since we will be making use of networking, streaming and threading objects, start by adding the following using statements:

using System.Net;

using System.Net.Sockets;

using System.IO;

using System.Threading;

We’re going to declare most of our objects inside the class, as private, since we don’t need them accessible from anywhere else outside the class:

// Will hold the user name

private string UserName = “Unknown”;

private StreamWriter swSender;

private StreamReader srReceiver;

private TcpClient tcpServer;

// Needed to update the form with messages from another thread

private delegate void UpdateLogCallback(string strMessage);

// Needed to set the form to a “disconnected” state from another thread

private delegate void CloseConnectionCallback(string strReason);

private Thread thrMessaging;

private IPAddress ipAddr;

private bool Connected;

And now that we have them declared, let’s put them to use. Let’s start with the btnConnect_Click event which can be automatically generated if you double click on the Connect button. Inside it we’re going to check whether or not we are connected to a server. If we are, we should call the method that initializes the connection, otherwise we call the method that closes the connection, also specifying a reason why to it:

private void btnConnect_Click(object sender, EventArgs e)

{

// If we are not currently connected but awaiting to connect

if (Connected == false)

{

// Initialize the connection

InitializeConnection();

}

else // We are connected, thus disconnect

{

CloseConnection(“Disconnected at user’s request.”);

}

}

All simple so far, so let’s move to InitializeConnection():

private void InitializeConnection()

{

// Parse the IP address from the TextBox into an IPAddress object

ipAddr = IPAddress.Parse(txtIp.Text);

// Start a new TCP connections to the chat server

tcpServer = new TcpClient();

tcpServer.Connect(ipAddr, 1986);

 

// Helps us track whether we’re connected or not

Connected = true;

// Prepare the form

UserName = txtUser.Text;

 

// Disable and enable the appropriate fields

txtIp.Enabled = false;

txtUser.Enabled = false;

txtMessage.Enabled = true;

btnSend.Enabled = true;

btnConnect.Text = “Disconnect”;

 

// Send the desired username to the server

swSender = new StreamWriter(tcpServer.GetStream());

swSender.WriteLine(txtUser.Text);

swSender.Flush();

 

// Start the thread for receiving messages and further communication

thrMessaging = new Thread(new ThreadStart(ReceiveMessages));

thrMessaging.Start();

}

Nothing too complicated happens in there. The IP address is parsed from the TextBox into an IPAddress object, and then we open a TCP connection to that address. The port is 1986 but it makes no difference as long as its free. We then prepare the controls on the form by disabling some and enabling the others. We also change the caption of btnConnect to now say Disconnect. Through a stream, we then tell the server which username we want, and immediately after that we start a new thread that calls the method ReceiveMessages() which will listen for incoming messages from now on. By putting this in a separate thread, our application is still fully usable while it is listening for messages from the server and keeping the connection alive.

It’s time to see what the ReceiveMessages() method is all about:

private void ReceiveMessages()

{

// Receive the response from the server

srReceiver = new StreamReader(tcpServer.GetStream());

// If the first character of the response is 1, connection was successful

string ConResponse = srReceiver.ReadLine();

// If the first character is a 1, connection was successful

if (ConResponse[0] == ‘1’)

{

// Update the form to tell it we are now connected

this.Invoke(new UpdateLogCallback(this.UpdateLog), new object[] { “Connected Successfully!” });

}

else // If the first character is not a 1 (probably a 0), the connection was unsuccessful

{

string Reason = “Not Connected: “;

// Extract the reason out of the response message. The reason starts at the 3rd character

Reason += ConResponse.Substring(2, ConResponse.Length – 2);

// Update the form with the reason why we couldn’t connect

this.Invoke(new CloseConnectionCallback(this.CloseConnection), new object[] { Reason });

// Exit the method

return;

}

// While we are successfully connected, read incoming lines from the server

while (Connected)

{

// Show the messages in the log TextBox

this.Invoke(new UpdateLogCallback(this.UpdateLog), new object[] { srReceiver.ReadLine() });

}

}

A new stream reader is hooked up to the TCP client. It will listen for incoming messages. But first of all, we read the first line coming from the server. The reason for that is that we know the first line contains a response telling us whether or not we connected successfully. Two reasons why we might’ve not connected successfully are if we attempted to use an username that is already taken, or if we attempted to use Administrator as the username, which is reserved for obvious purposes. The first character of the response given by the server tells us through a 1 that the connection was successful, and through a 0 if it was unsuccessful. And in that case, it also reads a reason as to why it was unsuccessful. That reason starts at the 3rd character of the message, since the first one is the number, and the second one is a pipe character. For example: 0|Username is already in use. Now you can see why if the first character is not a 1 we read the string that starts at the 3rd character and ends at the end of the line.

The this.Invoke() calls tell the form to update itself. We can’t directly update the form elements ourselves from this method because it’s in a separate thread (remember we called it using ThreadStart()) and cross-thread operations are illegal.

Finally, the while (Connected) loop keeps calling the srReceiver.ReadLine() method which checks for incoming messages from the server.

Next comes the method that we kept calling using this.Invoke() – all it does is to update the txtLog TextBox with the latest message:

// This method is called from a different thread in order to update the log TextBox

private void UpdateLog(string strMessage)

{

// Append text also scrolls the TextBox to the bottom each time

txtLog.AppendText(strMessage + “\r\n”);

}

So far we’ve seen how to receive messages from the server, but nothing about how to send them. When do we want to send a message? When the Send button is clicked or when the Enter key is pressed while txtMessage has the focus. This should be hooked up to the Click event of the btnSend button:

// We want to send the message when the Send button is clicked

private void btnSend_Click(object sender, EventArgs e)

{

SendMessage();

}

And this needs to be hooked up to the KeyPress event of txtMessage:

// But we also want to send the message once Enter is pressed

private void txtMessage_KeyPress(object sender, KeyPressEventArgs e)

{
// If the key is Enter

if (e.KeyChar == (char)13)

{

SendMessage();

}

}

You can see that both of them make a call to SendMessage, which we are going to see next:

// Sends the message typed in to the server

private void SendMessage()

{

if (txtMessage.Lines.Length >= 1)

{

swSender.WriteLine(txtMessage.Text);

swSender.Flush();

txtMessage.Lines = null;

}

txtMessage.Text = “”;

}

Quite simple, isn’t it? It just checks for the number of lines to be greater or equal to 1, and then writes that line to the TCP connection through the StreamWriter object. Calling Flush() ensures that the messages are being sent right away.

We seem to be almost done with the client application. But let’s not forget that when btnConnect was clicked, if we were already connected, we called a method called CloseConnection() – what happened to that? Well here it is:

// Closes a current connection

private void CloseConnection(string Reason)

{

// Show the reason why the connection is ending

txtLog.AppendText(Reason + “\r\n”);

// Enable and disable the appropriate controls on the form

txtIp.Enabled = true;

txtUser.Enabled = true;

txtMessage.Enabled = false;

btnSend.Enabled = false;

btnConnect.Text = “Connect”;

 

// Close the objects

Connected = false;

swSender.Close();

srReceiver.Close();

tcpServer.Close();

}

The form is being brought back to the not-connected state, and the TCP connection and streams are being closed. But what happens if the user doesn’t click Disconnect and just closes the application while the connection with the server is alive? We surely don’t want to leave the connection open like this till it dies by its own. Thankfully there is the ApplicationExit event that fires when the application closes, and that’s where we can close our connection. To hook up the event change your Form1 constructor to the following:

public Form1()

{

// On application exit, don’t forget to disconnect first

Application.ApplicationExit += new EventHandler(OnApplicationExit);

InitializeComponent();

}

And here is the event handler that does the actual disconnection:

// The event handler for application exit

public void OnApplicationExit(object sender, EventArgs e)

{

if (Connected == true)

{

// Closes the connections, streams, etc.

Connected = false;

swSender.Close();

srReceiver.Close();

tcpServer.Close();

}

}

Believe or not, we’re done with the chat client application. You should be able to compile and run it now, but of course there’s nothing to connect to because we haven’t developed the server. But that comes next in C# Chat: Part 2- Building the Chat Server. Here’s a little teaser of our applications in action, with the server in the shadow of the two:

Chat Clients