Internet programming----Chat Room


Environment: VC6 SP4, NT4 SP3, Win 2000


Introduction of networking programming

The most popular networking architecture is the client_ server model. The Client and the Server are software Applications: The server provides the services while the Client forwards the request for the user and get the services (response) from the Server.

The most important concept is properly the "Socket". Socket is like some point attached to both Client and Server side. Through the socket on the Server, the Client sends a request to the server and receives responses from the server. Through the socket on the client, the server gets the request from the client and sends the responds to the client.

The Socket plays like an agency. So, what is inside a socket? Socket is a data structure. Obviously, taking the connect oriented network as an example, we need to know at least the IP address and Port* of the remote machine that we want to connect .

(NOTE: We cant say most networking programs use the TCP/IP protocol sets, but many do. When TCP/IP is employed, we must have it in mind that TCP/IP transportation layer use PORT to interact with applications. Actually, many well known applications have default ports:


  • DAYTIME (13)
  • FTP (21)
  • TELNET (23)
  • SMTP (25)
  • WHOIS (43)
  • FINGER (77)
  • WEBSERVER (80)

They are called well_known ports . If you are developing a FTP server/Client, youd better use 21 as your applications port.)

When Socket was developed in Berkerly by Bill Joy or Winsock developed in Microsoft by some other big shots, the details of communication between socket and TCP/IP were hided. Developers use socket to communicate with a remote computer , as a matter of fact, they are using the TCP/IP protocol sets without necessarily knowing them. One can only find some trial from the parameters like "AF_INET", "PF_INET", IP address.

Simple steps of using socket:

  1. WSAstartup; //that is the initial work to launch a socket programming;
  2. Socket_Handle = socket(protocol family, socket type, protocol);


    protocol family : PF_INET;

    socket type: SOCK_STREAM (connect oriented) SOCK_DATAGRAM (connectless oriented) Protocol: IPPROTO_TCP

    NOTE: We have allocated some space for the socket in the memory now, but its still empty.

  3. Construct a socket address data structure (SocketAddr) , its members are including the IP address, ports and protocol type.

    (For the client application ,for example, try to find out the local machines IP; If your client application is a web browser, the port would be 80, protocol is AF_INET).

  4. Bind. Use the function bind to combine step 2 and step 3 together, then the socket is no longer empty, it has something meaningful inside.

From here, Server and Client begin to differ in the following procedure: Take an example of connect oriented communication , things go like this:

Server:           Client:           

We can see the on the client side, the "bind" is unnecessary. Once it's connected to a Server, it's socket address information can be thrived from the server.


Multithread is crucial in the networking programming.

For the client, while it's attempting to connect the server, surely you don't wait for the time idle by, but in a single thread application, you'll find it's "dead" in responding your action.( By the way, the TELNET program for Win98/NT is a bad example, which is obviously a single thread application, you can try moving it while it's performing the connection) .

While it's still workable for a single thread client,  the Server must be a multithread one. Each secession with the client, each single connection, is a thread. They are all the worker threads attached to the server application. There would be conflict among the clients' connection if they don't have their own thread.

The chat room application

I have to say that there would be some other better technology stuff about the internet programming, actually you can also see an article about the chat room on with ATL. But I think this intuitive MFC implementation would suit most readers.

But not totally from ground up. I read  David J. Kruglinski'sclassical "Inside visual C++"  and used the thin_wrapped classes of raw internet API from his book. I'm not sure if it's better than the ones provided by MFC as declared , but it works well.

There are actually  two applications: Server and Client. You have to launch  the server first, then distribute your client copies to other machines. 

NOTE:  You have to modify the client's code manually : change the server's IP address string to your own server's address ( in the beginning of "Utility.cpp" of Client project, see the comment there) before compiling it. 

If you don't know what your server's IP address is, select server's menu : Connection/Local IP Address .

Several things have to be attended when you are playing the "Chat room":

  1. The server must be launched first, select the menu "connection/start server", then goes the Client;
  2. As soon as the Client is launched, it's attempting to connect the server;
  3. Login with an user name;
  4. Begin to talk, you can use the RETURN key instead of the "Go!" button, it's more efficient.

This application is far from perfect, for example, you can see it's not robust enough to prevent the simultaneously access of the global variables.  I made it as simple as possible to be understood. Only the necessary implementations are preserved. I am improving it on my site from time to time. You are welcome to stop by to see my progress.

Enjoy it!

Code (Just flowchart)

  1. Connection;
  2. Server loop: Listening->Get request ->Parse request->Form response->Send back;
  3. Client loop: Get response->Parse response->Send it to the appropriate controls to interact with the user.

Read the comments in the code for more details.


Download Server project [59KB]

Download Client project [44KB]


  • Assistance

    Posted by jo on 03/15/2016 01:33pm

    Hi, I need help with my program project, please respond if you can help me. Thanks Jo

  • .net

    Posted by San on 08/29/2015 02:23am

    Hi Everybody Does any body know how to create a 'Page Object' register view? Thanks I am using visual studio C#.

  • Comprar ghd línea rápido envío, venta, barato

    Posted by txhtxd495 on 07/17/2013 04:33am

    Hoy en dia, hay muchas herramientas para que podamos hacer nuestro cabello más la plancha ghd es nuestra mejor opción, ya que puede tener el pelo más sano y fashion.I sugieren se lava el cabello y secarlo completamente antes de uso de alisadores. Si usted utiliza el pelo o cualquier otro planchas de pelo, causarán daños reparables para el cabello que está húmeda o no completamente tør.Vi ofrecen muchos tipos de Babyliss baratos GHD, marca de plancha de pelo ghd baratas, nueva llegada, descuento planchas ghd, etc nuevos estilos, buen precio, varios colores, entrega rápida, orden de la pequeña cantidad accepteret.Efter mi opinión, que vuelve a alegrar por la noticia de que ghd está preparado para you.All la ghd es muy chi y barato con una calidad superior. son absolutamente el mejor producto en el mercado. [url=]planchas GHD España[/url] Para proteger sus derechos, por favor ingrese cartero comprobar personalmente los productos antes y tipos de productos, la cantidad, el tamaño, la cantidad es de acuerdo con la orden, tal y como sign.After de firmar, la ocurrencia de estos fenómenos ya no será for.Part responsables de participar en la moda, no sólo es el intercambio intelectual, más que un espectáculo y te pones el pelo singular, las mujeres de moda serán cada uno de su partido, ideas personales, saben qué ponerse, qué tipo de efecto. Así que si usted asiste a una fiesta de la moda, por lo que el nuevo peinado fresco es su elección.撤消修改Alpha [url=]GHD España[/url] Popular plancha de pelo ghd es de los mejores expertos en el cuidado del cabello, por lo que es una buena elección de estilos que te gustan. Siempre se puede cambiar su peinado. Que toda su apariencia se ha convertido en más estrellas fremragende.Mange también como las herramientas de diseño. Debido a que es fácil de llevar. Puede ser bien utilizados. Fácil de manejar, se transforma. Profesional ghd también necesitan los profesionales a vender. No entiendo cómo se utiliza el mismo tiempo, usted puede hacer preguntas, usted puede saber en un tiempo y lugar diferente que desea saber. Vendemos planchas ghd son los mejores porque hemos sido a través de muchos años de funcionamiento y la práctica. La gente tiene que entender lo que ghd estilo. Productos de cuidado personal. Por lo tanto, creemos en que seremos el mejor socio.

  • Problem with php script

    Posted by Bartek Talik on 06/16/2013 08:45am

    Hi there I wrote a function in HTML than I put it to the php and when I try to run it I have index undefined and variables as well and in php it look like this ?php $Carvalue=$_POST['carValue]; $quote=$_POST['quote']; If ($carVallue = 1000) { echo " $quote = $quote + 100 "; } else if ($carValue 1000 && $carValue $quote = $quote +200 "; } ?> There are more variables but I want to be sure this above is correct?I get index and variables undefined and don't know why?Please write me back ASAP.

  • Lilla GHD glattejern til en billig pris

    Posted by carpinteyroafv on 06/14/2013 01:14pm

    [url=]glattejern ghd[/url] Alle os gøre en indsats for at virke som den største og kan udføre noget, der kan gøres for at forbedre synlige look. Der er ikke noget, et parti der kan gøres med hensyn til at forbedre din egen økologiske tiltrækningskraft, men du sikkert kan udføre nogle ting for at forbedre den faktiske appel fra den fantastiske overhead i forbindelse med låse, du har opnået. Du skal bruge Opretning Irons til at øge det beløb, samt skær af låsene. Den allerbedste fabrikat af håret i øjeblikket er tilgængelige er skabt gennem ghd. Du kan være sikker på du vil have en stor møde, når du glatte hår ved at udnytte ghd hår glatning jern. ghd hår Dansk Ion låser Re-teksturering eller endda IHR er faktisk i disse dage nok den mest sofistikerede låse styling teknik, der blev oprettet i Asien. Denne metode kræver periode, og det bruges kun inden for låse saloner siden teknologier medfører ikke så let procedure. Ioner har tendens til at få lov til at trænge til håret foillicle af hver låse til at ændre sin forandring. [url=]Glattejern ghd pris[/url] Men håret er ikke det samme, hvis de tager sig af det, kun så få hår. Lille variation, du går til frisør, men også tager lang tid at vente. For at starte hår udnævnelser. Det er spild af tidskrævende indsats. Nogle gange håret er ikke at gøre hvad du ønsker. Her har vi indføre et ghd glattejern produkt, er det en god hår pleje produkter, elegant udseende, ædle farver, enkel betjening, til enhver tid at ændre din frisure. Keramisk hot lige, vil dit hår ikke bringe noget ondt, men også hjælper forskønne dit hår. Her i Danmark sælger vi ghd glattejern er den billigste, garanteret at være ægte ghd. Sørg for at bruge det liv og ejendom sikkerhed. [url=]Glattejern ghd[/url] Ligesom enhver anden hårudglatningsmiddel i ghd hår stabil, den metalliske Collection glattejern garanteret sikker at bruge. De er drevet ved hjælp universel spænding, hvilket gør dem praktisk for styling farten. De metalliske serien stylers også komme med en varme-bevis sag og en to-årig garantiperiode.Den Metallic Collection indeholder tre ghd glattejern med et slankt og skinnende finish. De er nemlig: ghd skinnende Silver Metallic Series Styler, ghd Rich Ruby Red Metallic Series Styler, og ghd Sahara Gold Metallic Series Styler.Hver ghd glattejern i Metallic Collection har de samme innovative funktioner som den klassiske ghd guld V glattejern, en af de bedst sælgende stylers i ghd produktlinje. Disse stylers er velegnede til alle hårtyper. Også med deres keramisk varmelegeme teknologi designet til at forsegle fugt i individuelle hår tråde, er disse stylers alle garanteret til at give ekstra glans og glans til håret, hvad enten det er krøllet, vinkede eller stryges lige.

  • Nike Air Max+instagram, desire you contain the color to be in on your feet!

    Posted by madytreathy on 04/19/2013 08:52pm

    Remember in 2008, if not earlier, when Nike launched ahead of the self-assured shoe color projects, the watchword "Scion Your Colours", "Nike PhotoiD" scheme, [url=]nike free run uk[/url] reply has not been as enthusiastic as expected. Have in mind, 2008 Canon IXUS 80 IS Digital file card arcade but contrariwise 8 million pixels, Nokia, the facile phone superstore is the one governorship, NikeiD was boost to color in the photos as a basis for sneakers duty color, although gripping, but does trouble some. Instagram which sort this item fun and elemental, Nike PHOTOiD homeopathic upgrade customization services, recently [url=]nike free run[/url] released a strange plan. That such iD can you implement pictures as instagram account shoe color, for a short offer Nike Air Max shoes and Nike Style Max 1, Nike Affectedness Max 90 953 options. Interested in children's shoes, you [url=]nike huarache free[/url] can ever conform with each other's valid website, in reckoning to skim through other people's artistic sweat, or you can try to upload your own instagram photo, erect your own Nike Air Max.

  • Its Great

    Posted by Legacy on 01/16/2004 12:00am

    Originally posted by: Sudhanshu Saxena


    Thanks for the help.


  • Why it don`t work?

    Posted by Legacy on 09/12/2003 12:00am

    Originally posted by: Xinbai

    There are more than one Netword Adapt in my computer, when i try to run the chat programe, the client application couldn`t work, the return value is 10061,why?

    The following description is from MSDN
    Connection refused.
    No connection could be made because the target machine actively refused it. This usually results from trying to connect to a service that is inactive on the foreign host--that is, one with no server application running.

  • big message

    Posted by Legacy on 10/08/2002 12:00am

    Originally posted by: hihi

    failed when the client sends big message.

  • In case of sudden powershut down,how to trace whether client is offline?

    Posted by Legacy on 09/14/2002 12:00am

    Originally posted by: AnushaIyer

    Nice Job Buddy!..but just i'd pleased if u answer me for this Question.
    "Incase if client goes offline how 2 detect it?"
    "Is there any provision to store offline msgs?"

  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • As all sorts of data becomes available for storage, analysis and retrieval - so called 'Big Data' - there are potentially huge benefits, but equally huge challenges...
  • The agile organization needs knowledge to act on, quickly and effectively. Though many organizations are clamouring for "Big Data", not nearly as many know what to do with it...
  • Cloud-based integration solutions can be confusing. Adding to the confusion are the multiple ways IT departments can deliver such integration...

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date