a chat application using asynchronous tcp socketsdinus.ac.id/repository/docs/ajar/a chat application...

7
9,697,537 members (26,357 online) Sign in home quick answers discussions features community help Search for articles, questions, tips Articles » General Programming » Internet / Network » Client/Server Development Article Browse Code Stats Revisions Alternatives Comments & Discussions (76) About Article This article will discuss a chat application using asynchronous TCP sockets, in C#. Type Article Licence First Posted 28 Dec 2006 Views 205,204 Bookmarked 207 times C# Windows .NET Visual-Studio Dev , + Top News The true power of regular expressions Get the Insider News free each morning. Next A Chat Application Using Asynchronous TCP Sockets By Hitesh Sharma, 28 Dec 2006 Download source - 28.6 Kb Introduction In this article, I will discuss a chat application using asynchronous TCP sockets in C#. In the next part of this article, I will present an asynchronous UDP socket based chat application. TCP Asynchronous Sockets TCP asynchronous sockets have a Begin and End appended to the standard socket functions, like BeginConnect , BeginAccept , BeginSend , and BeginReceive . Let's take a look at one of them: Collapse | Copy Code IAsyncResult BeginAccept(AsyncCallback callback, object state); The AsyncCallback function is called when the function completes. Just as events can trigger delegates, .NET also provides a way for methods to trigger delegates. The .NET AsyncCallback class allows methods to start an asynchronous function and supply a delegate method to call when the asynchronous function completes. The state object is used to pass information between the BeginAccept and the corresponding AsyncCallback function. The following shows an implementation of it: Collapse | Copy Code Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050 ); sock.Bind (iep); sock.Listen ( 5 ); sock.BeginAccept ( new AsyncCallback(CallAccept), sock); private void CallAccept(IAsyncResult iar) { 4.91 (33 votes) articles

Upload: phamthien

Post on 27-Aug-2018

237 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: A Chat Application Using Asynchronous TCP Socketsdinus.ac.id/repository/docs/ajar/a chat application using... · Related Articles A Chat Application Using Asynchronous UDP sockets

9,697,537 members (26,357 online)

Sign in

home quick answers discussions features community help Search for articles, questions, tips

Articles » General Programming » Internet / Network » Client/Server Development

Article

Browse Code

Stats

Revisions

Alternatives

Comments &Discussions (76)

About Article

This article will discuss achat application usingasynchronous TCP sockets,in C#.

Type Article

Licence

First Posted 28 Dec 2006

Views 205,204

Bookmarked 207 times

C# Windows .NET

Visual-Studio Dev , +

Top News

The true power of regular

expressions

Get the Insider News free eachmorning.

Next

A Chat Application Using Asynchronous TCP

SocketsBy Hitesh Sharma, 28 Dec 2006

Download source - 28.6 Kb

Introduction

In this article, I will discuss a chat application using asynchronous TCP sockets in C#. In the next part of

this article, I will present an asynchronous UDP socket based chat application.

TCP Asynchronous Sockets

TCP asynchronous sockets have a Begin and End appended to the standard socket functions, like

BeginConnect, BeginAccept, BeginSend, and BeginReceive. Let's take a look at one of them:

Collapse | Copy Code

IAsyncResult BeginAccept(AsyncCallback callback, object state);

The AsyncCallback function is called when the function completes. Just as events can trigger delegates,

.NET also provides a way for methods to trigger delegates. The .NET AsyncCallback class allows

methods to start an asynchronous function and supply a delegate method to call when the asynchronous

function completes.

The state object is used to pass information between the BeginAccept and the corresponding

AsyncCallback function.

The following shows an implementation of it:

Collapse | Copy Code

Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);sock.Bind (iep);sock.Listen (5);sock.BeginAccept (new AsyncCallback(CallAccept), sock);

private void CallAccept(IAsyncResult iar){

4.91 (33 votes)

articles

Page 2: A Chat Application Using Asynchronous TCP Socketsdinus.ac.id/repository/docs/ajar/a chat application using... · Related Articles A Chat Application Using Asynchronous UDP sockets

Related Articles

A Chat Application UsingAsynchronous UDP sockets

LanTalk

TCP/IP Chat Application UsingC#

Programming Windows TCPSockets in C++ for the Beginner

Asynchronous socketcommunication

A Complete TCP Server/ClientCommunication and RMIFramework - Usage

Multi-threaded Client/ServerSocket Class

Multithreaded Chat Server

A Complete TCP Server/ClientCommunication and RMIFramework in C# .NET -Implementation

Working with Sockets in C#

Push Framework - A C++toolkit for high performanceserver development

Your First Step to the SilverlightVoice/Video ChattingClient/Server

Full Multi-thread Client/ServerSocket Class with ThreadPool

Beginning WinsockProgramming - MultithreadedTCP server with client

ZeroMQ via C#: Introduction

CCESocket: a general purposeTCP/UDP socket class forWinCE

Asynchronous SocketCommunications Using the.NET Framework

Beginning WinsockProgramming - Simple TCPclient

Multithreaded TCP/IP TelnetServer - Chess Game Example

Offset weaknesses of DCOMwith strong points of socket

Socket server = (Socket)iar.AsyncState; Socket client = server.EndAccept(iar);}

The original sock object is retrieved in CallAccept by using the AsyncState property of

IAsyncResult. Once we have the original socket (on which the operation completed), we can get the

client socket and perform operations on it.

All other asynchronous socket functions work like this, you should look on MSDN for further details.

There are a few nice articles explaining the details on the net, so kindly search for them as well.

Getting Started

For exchange of messages between the client and the server, both of them use the following trivial

commands:

Collapse | Copy Code

//The commands for interaction between the server and the clientenum Command{ //Log into the server Login, //Logout of the server Logout, //Send a text message to all the chat clients Message, //Get a list of users in the chat room from the server List}

The data structure used to exchange data between the client and the server is shown below. Sockets

transmit and receive data as an array of bytes; the overloaded constructor and the ToByte member

function performs this conversion.

Collapse | Copy Code

//The data structure by which the server and the client interact with //each otherclass Data{ //Default constructor public Data() { this.cmdCommand = Command.Null; this.strMessage = null; this.strName = null; }

//Converts the bytes into an object of type Data public Data(byte[] data) { //The first four bytes are for the Command this.cmdCommand = (Command)BitConverter.ToInt32(data, 0);

//The next four store the length of the name int nameLen = BitConverter.ToInt32(data, 4);

//The next four store the length of the message int msgLen = BitConverter.ToInt32(data, 8);

//Makes sure that strName has been passed in the array of bytes if (nameLen > 0) this.strName = Encoding.UTF8.GetString(data, 12, nameLen); else this.strName = null;

//This checks for a null message field if (msgLen > 0) this.strMessage = Encoding.UTF8.GetString(data, 12 + nameLen, msgLen); else this.strMessage = null; }

//Converts the Data structure into an array of bytes public byte[] ToByte() { List<byte> result = new List<byte>();

//First four are for the Command result.AddRange(BitConverter.GetBytes((int)cmdCommand));

//Add the length of the name if (strName != null) result.AddRange(BitConverter.GetBytes(strName.Length)); else result.AddRange(BitConverter.GetBytes(0));

//Length of the message if (strMessage != null) result.AddRange(BitConverter.GetBytes(strMessage.Length)); else result.AddRange(BitConverter.GetBytes(0));

//Add the name

Page 3: A Chat Application Using Asynchronous TCP Socketsdinus.ac.id/repository/docs/ajar/a chat application using... · Related Articles A Chat Application Using Asynchronous UDP sockets

if (strName != null) result.AddRange(Encoding.UTF8.GetBytes(strName));

//And, lastly we add the message text to our array of bytes if (strMessage != null) result.AddRange(Encoding.UTF8.GetBytes(strMessage));

return result.ToArray(); }

//Name by which the client logs into the room public string strName; //Message text public string strMessage; //Command type (login, logout, send message, etc) public Command cmdCommand;}

TCP Server

The server application listens on a particular port and waits for the clients. The clients connect to the

server and join the room. The client then sends a message to the server, the server then sends this to all

the users in the room.

The server application has the following data members:

Collapse | Copy Code

//The ClientInfo structure holds //the required information about every//client connected to the serverstruct ClientInfo{ //Socket of the client public Socket socket; //Name by which the user logged into the chat room public string strName;}

//The collection of all clients logged //into the room (an array of type ClientInfo)ArrayList clientList;

//The main socket on which the server listens to the clientsSocket serverSocket;

byte[] byteData = new byte[1024];

Here is how it starts listening for the clients and accepts the incoming requests:

Collapse | Copy Code

private void Form1_Load(object sender, EventArgs e){ try { //We are using TCP sockets serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //Assign the any IP of the machine and listen on port number 1000 IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, 1000);

//Bind and listen on the given address serverSocket.Bind(ipEndPoint); serverSocket.Listen(4);

//Accept the incoming clients serverSocket.BeginAccept(new AsyncCallback(OnAccept), null); } catch (Exception ex) { MessageBox.Show(ex.Message, "SGSserverTCP", MessageBoxButtons.OK, MessageBoxIcon.Error); }}

With IPAddress.Any, we specify that the server should accept client requests coming on any interface.

To use any particular interface, we can use IPAddress.Parse (“192.168.1.1”) instead of

IPAddress.Any. The Bind function then bounds the serverSocket to this IP address. The Listen

function makes the server wait for the clients, the value passed to Listen specifies how many incoming

client requests will be queued by the operating system. If there are pending client requests and another

comes in, then it will be rejected.

Below is the corresponding OnAccept function:

Collapse | Copy Code

private void OnAccept(IAsyncResult ar){ try { Socket clientSocket = serverSocket.EndAccept(ar);

//Start listening for more clients

Page 4: A Chat Application Using Asynchronous TCP Socketsdinus.ac.id/repository/docs/ajar/a chat application using... · Related Articles A Chat Application Using Asynchronous UDP sockets

serverSocket.BeginAccept(new AsyncCallback(OnAccept), null);

//Once the client connects then start //receiving the commands from her clientSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(OnReceive), clientSocket); } catch (Exception ex) { MessageBox.Show(ex.Message, "SGSserverTCP", MessageBoxButtons.OK, MessageBoxIcon.Error); }}

EndAccept returns the clientSocket object of the connecting client. We then again start listening for

more incoming client requests by making a call to serverSocket.BeginAccept; this is essential as the

server won’t be able to process any other incoming client request without it.

With BeginReceive we start receiving the data that will be sent by the client. Note that we pass

clientSocket as the last parameter of BeginReceive; the AsyncCallback OnReceive gets this

object via the AsyncState property of IAsyncResult, and it then processes the client requests (login,

logout, and send messages to the users). Please see the code attached to understand the implementation

of OnReceive.

TCP Client

Some of the data members used by the client are:

Collapse | Copy Code

//The main client socketpublic Socket clientSocket;//Name by which the user logs into the roompublic string strName;

private byte[] byteData = new byte[1024];

The client firstly connects to the server:

Collapse | Copy Code

try{ //We are using TCP sockets clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

IPAddress ipAddress = IPAddress.Parse(txtServerIP.Text); //Server is listening on port 1000 IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 1000);

//Connect to the server clientSocket.BeginConnect(ipEndPoint, new AsyncCallback(OnConnect), null);}catch (Exception ex){ MessageBox.Show(ex.Message, "SGSclient", MessageBoxButtons.OK, MessageBoxIcon.Error); }

Once connected, a login message is sent to the server. And after that, we send a list message to get the

names of clients in the chat room.

Collapse | Copy Code

//Broadcast the message typed by the user to everyoneprivate void btnSend_Click(object sender, EventArgs e){ try { //Fill the info for the message to be send Data msgToSend = new Data(); msgToSend.strName = strName; msgToSend.strMessage = txtMessage.Text; msgToSend.cmdCommand = Command.Message;

byteData = msgToSend.ToByte();

//Send it to the server clientSocket.BeginSend (byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(OnSend), null);

txtMessage.Text = null; } catch (Exception) { MessageBox.Show("Unable to send message to the server.", "SGSclientTCP: " + strName, MessageBoxButtons.OK, MessageBoxIcon.Error); }

Page 5: A Chat Application Using Asynchronous TCP Socketsdinus.ac.id/repository/docs/ajar/a chat application using... · Related Articles A Chat Application Using Asynchronous UDP sockets

Article Top

1 TweetTweet 0

Sign Up to vote Poor Excellent Vote

Search this forum Go

}

The message typed by the user is send as a command message to the server which then sends it to all

other users in the chat room.

Upon receiving a message, the client processes it accordingly (depending on whether it’s a login, logout,

command, or a list message). The code for this is fairly straightforward, kindly see the attached project.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the

download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Hitesh

Sharma

United States

Member

No Biography provided

Comments and Discussions

You must Sign In to use this message board.

Profile popups Spacing Relaxed Noise Very High Layout Open All Per page 10

Update

First Prev Next

WissamSoft 8 Feb '13 - 8:13

Hi,

i think something wrong with the ToByte() convertion. Messagebox(strMessage.length.toSring())

give a wrong size of strMessage. i think you have to set the startindex in the array.

|Command|NameLength|MessageLength|strName|strMessage|

4 bytes 4 bytes 4 bytes

So the ToByte() Method has to put the values on the right position!

byte[] ToSend[] = new byte[12 + strName.length + strMessage.length];

byte[] Command = BitConverter.GetBytes((int)cmdCommand);

byte[] NameLength = BitConverter.GetBytes(strName.length);

...............

..........

Like 0

public byte[] ToByte()

Page 6: A Chat Application Using Asynchronous TCP Socketsdinus.ac.id/repository/docs/ajar/a chat application using... · Related Articles A Chat Application Using Asynchronous UDP sockets

Command.CopyTo(ToSend,0);

NameLength.CopyTo(ToSend,4);

.......

.............

return ToSend;

Sign In · View Thread · Permalink

zhilongjiang 24 Jan '13 - 17:23

That's exactly what I want. Thank you so much.

Sign In · View Thread · Permalink

manu018 7 Jun '12 - 1:20

I am using this demo application and create Client application setup. when i installed in XP then

working fine but it does't work in window7. show given below error message:

1.(.msi):This installation package could not be opened. Contact the application vendor to verify

that this is a valid windows installer package

2.(.exe):Setup.exe is not a valid Win32 application

Please help to solve this issue.

Thanks in Advance

fsfsdfsdfsdfsdfsdf

sdfsdfsdfs

df

sd

f

sd

fsd

fs

dfsd

fsd

fsdf

sdf

sd

Sign In · View Thread · Permalink

lamabao 14 Apr '12 - 5:00

after i run progam "Cross-thread operation not valid: Control 'txtlog' accessed from a thread

other than the thread it was created on".i can help me

Sign In · View Thread · Permalink

GregoryHannah 15 Apr '12 - 4:56

In the form load set the following to false:

Control.CheckForIllegalCrossThreadCalls = False

Sign In · View Thread · Permalink

lamabao 15 Apr '12 - 16:08

thanks.

Sign In · View Thread · Permalink

guagmingleng 25 Dec '11 - 18:22

Thanks for your great program,it's very useful for me, i have a question to ask,can you help me .

For the server, i wanna accept up to 100+ client connections ,can your program server do that in

high performance?

and how to implement one-client-one-thread connection in server.since when one task want to

My vote of 5

Compatibility Issue with Window7.

Cross-thread operation not valid: Control

'txtlog' accessed from a thread other than

the thread it was created on

Re: Cross-thread operation not valid:

Control 'txtlog' accessed from a thread

other than the thread it was created on

Re: Cross-thread operation not valid:

Control 'txtlog' accessed from a

thread other than the thread it was

created on

Can you do me favor,thanks so much!

Page 7: A Chat Application Using Asynchronous TCP Socketsdinus.ac.id/repository/docs/ajar/a chat application using... · Related Articles A Chat Application Using Asynchronous UDP sockets

Permalink | Advertise | Privacy | Mobile Web04 | 2.6.130228.2 | Last Updated 28 Dec 2006

Article Copyright 2006 by Hitesh SharmaEverything else Copyright © CodeProject, 1999-2013

Terms of Use

Layout: fixed | fluid

spend long time to handle,other message will be ingored.

Sign In · View Thread · Permalink

aida Salvador 14 Dec '11 - 17:26

hola, en realidad el programa me parecio muy interesante, pero me gustaria saber como obtengo

la direccion IP de los clientes que se conectan....

Sign In · View Thread · Permalink

carazuza 7 Nov '12 - 9:47

creo que lo tenés en clientSocket.RemoteEndPoint

Sign In · View Thread · Permalink

bleachli 9 Nov '11 - 15:31

thank U

Sign In · View Thread · Permalink

Last Visit: 31 Dec '99 - 19:00 Last Update: 1 Mar '13 - 9:14 Refresh 1 2 3 4 5 6 7 8 Next »

General News Suggestion Question Bug Answer Joke Rant Admin

Como conocer la IP del cliente

Re: Como conocer la IP del cliente

thank U