Click here to Skip to main content
5,788,212 members and growing! (19,399 online)
Email Password   helpLost your password?
Desktop Development » Miscellaneous » General     Beginner License: The Code Project Open License (CPOL)

Simple Messenger - A C# MSN Messenger like chat application

By HarrisonZhuo

This is a MSN Messenger like chat application using C# with TCP/IP socket programming.
C# (C# 2.0, C# 3.0, C#), .NET, Visual Studio (Visual Studio, VS2008, VS2005)

Posted: 10 Jul 2008
Updated: 10 Jul 2008
Views: 10,120
Bookmarked: 43 times
Note: This is an unedited reader contribution
Announcements
Loading...



Search    
Advanced Search
Sitemap
9 votes for this Article.
Popularity: 3.68 Rating: 3.86 out of 5
0 votes, 0.0%
1
1 vote, 11.1%
2
4 votes, 44.4%
3
0 votes, 0.0%
4
4 votes, 44.4%
5
Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else's work without reference then please Report This Article
SimpleMessenger_--_CodeProject

Introduction

This is a simple MSN Messenger like chat application using socket programming. It allows the users to send and receive messenges by running two Simple Messengers.

TherThere are two specific features that other than the regular MSN Messenger:

1. 'Hex':
TRUE: The data will be displayed in Hex format.
FALSE: The data will be displayed in regular text.

2. 'No print on receiving':
TRUE: The received data will not be printed on the textbox.
FALSE: The received data will be printed on the textbox as normal.

Background

One day when I was working on the socket programming, I need to monitor the data transmission. Although the Visual Studio already have the debugger for the user to monitor the data, I still need a third application to cache the data and take a look at them. This comes with the idea for the Simple Messenger.You can use this program as a chat application when you run two Simple Messengers. If you connect your computer to a device, another software, a web application, etc., you will be able to send/receive data via one Simple Messenger. In my case, I just connect my computer to a device which has Ethernet connection and I need to monitor the data sent by the device without interrupting it. The main purpose of this article here is to share this program with you and for me to learn the socket programming and multiple threads.

KeyValuePair

A helper class wraps a Socket and an array of byte.

public class KeyValuePair
{
    public Socket socket;
    public byte[] dataBuffer = new byte[1];
} 

Connection

The connection is slightly different between the Server Mode and the Client Mode.

First look at the Server Mode:

if (radioButton1.Checked == true)//Server Mode
{
    //Console.WriteLine("Server Mode");
    try
    {
        //create the listening socket...
        server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, 
                            ProtocolType.Tcp);
        IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, Convert.ToInt16(port));

        server.Bind(ipLocal);//bind to local IP Address...
        server.Listen(10);//start listening...

        //create the call back for any client connections...
        server.BeginAccept(new AsyncCallback(OnClientConnect), null);
        /* ... */ 
}
catch (SocketException se)
{
    MessageBox.Show("Server Connect Error.\r\n" + se.ToString());
}

The server needs to watch for the connection that if there is any client trying to connect to it.

public void OnClientConnect(IAsyncResult asyn)
{
    try
    {
        server = server.EndAccept(asyn);
        WaitForData(server);
    } 
    /* ... */ 
} 

Before the server socket receives any data, we must prepare for it ahead. Here the KeyValuePair object is imported as a parameter.

public void WaitForData(Socket soc)
{
    try
    {
        if (asyncCallBack == null) asyncCallBack = new AsyncCallback(OnDataReceived);

        KeyValuePair aKeyValuePair = new KeyValuePair();
        aKeyValuePair.socket = soc;

        // now start to listen for incoming data...
        aKeyValuePair.dataBuffer = new byte[soc.ReceiveBufferSize]; 
        soc.BeginReceive(aKeyValuePair.dataBuffer, 0, aKeyValuePair.dataBuffer.Length, 
                     SocketFlags.None, asyncCallBack, aKeyValuePair);
    } 
    /* ... */ 
} 

Now look at the Client Mode:

else if (radioButton2.Checked == true)//Client Mode
{
    //Console.WriteLine("Client Mode");
    try
    {
        client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, 
                            ProtocolType.Tcp);
        IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(ipAddr), Convert.ToInt16(port));
        client.Connect(ipe);
        clientListener = new Thread(OnDataReceived);
        isEndClientListener = false;
        clientListener.Start(); 
        /* ... */
}
catch (SocketException se)
{
    MessageBox.Show("Client Connect Error.\r\n" + se.ToString());
}

Data Receive

Since the AsyncCallback is used for the server, receiving the data will be different.

For the Server Mode:

KeyValuePair aKeyValuePair = (KeyValuePair)asyn.AsyncState;
//end receive...
int iRx = 0;
iRx = aKeyValuePair.socket.EndReceive(asyn);
if (iRx != 0)
{
    byte[] recv = aKeyValuePair.dataBuffer;
}

For the Client Mode:

byte[] recv = new byte[client.ReceiveBufferSize];//you can define your own size 
int iRx = client.Receive(recv );
if (iRx != 0)
{
    //recv should contains the received data.
}

Data Send

Sending the data is as easy as calling the Send() method comes with the Socket. e.g.

soc.Send(dataBytes);//'soc' could either be the server or the client

Points of Interest

Everytime I use the MSN Messenger to chat with my friends, I'm worried that if my conversation will be recorded by 'MSN' or not. Now I'm happy and 'safe' to use my own chat application to chat with my friends, er... within a local network. However, the main benefit of this program is that I learned how to play with the Ethernet and the sockets. I hope this will benefit you as well.

History

  • July 2 - First Version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

HarrisonZhuo



Occupation: Software Developer
Company: BTI
Location: Canada Canada

Other popular Miscellaneous articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 6 of 6 (Total in Forum: 6) (Refresh)FirstPrevNext
Generalnot working for other computers within local networkmemberharikrishna21019:30 17 Nov '08  
GeneralRe: not working for other computers within local network [modified]memberHarrisonZhuo6:09 18 Nov '08  
GeneralRe: not working for other computers within local networkmemberharikrishna21023:30 18 Nov '08  
GeneralRe: not working for other computers within local networkmemberHarrisonZhuo8:35 20 Nov '08  
GeneralThreading [modified]memberTaner Riffat15:41 10 Jul '08  
GeneralRe: ThreadingmemberHarrisonZhuo11:15 25 Aug '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 10 Jul 2008
Editor:
Copyright 2008 by HarrisonZhuo
Everything else Copyright © CodeProject, 1999-2009
Web15 | Advertise on the Code Project