Internet programming----Chat Room

.

Environment: VC6 SP4, NT4 SP3, Win 2000

Content

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:

ECHO 7

  • DAYTIME (13)
  • FTP (21)
  • TELNET (23)
  • SMTP (25)
  • TIMESERVER (37)
  • NAMESERVER (42)
  • 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);

    eg.:

    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:           
Socket()Socket()
bind() 
listen() 
accept()Connect()
read()Write()
write()Read()

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

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 http://www.codeguru.com/internet/UniTalk2.html 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 www.geocities.com/sawyhandyee 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.

Downloads

Download Server project [59KB]

Download Client project [44KB]



Comments

  • 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 style.men 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=http://planchaspeloghdes.qsite.dk/]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 ghdglattejernblog.com 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=http://comprarghd.webgarden.com/]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.

    Reply
  • 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.

    Reply
  • Lilla GHD glattejern til en billig pris

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

    [url=http://www.glattejernghd.350.com/]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=http://glattejernghdpris.webgarden.es/]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=http://glattejernghd.bloguedobebe.com/]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.

    Reply
  • 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=http://northernroofing.co.uk/roofins.cfm]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=http://markwarren.org.uk/goodbuy.cfm]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=http://fossilsdirect.co.uk/glossarey.cfm]nike huarache free[/url] can ever conform with each other's valid website photoid.Nike.com, 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.

    Reply
  • Its Great

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

    Originally posted by: Sudhanshu Saxena

    Hi,

    Thanks for the help.

    Thanks,
    Sudhanshu

    Reply
  • 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
    WSAECONNREFUSED
    (10061)
    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.

    Reply
  • big message

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

    Originally posted by: hihi

    failed when the client sends big message.

    Reply
  • 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?"

    Reply
  • linker errors

    Posted by Legacy on 06/23/2002 12:00am

    Originally posted by: gwyn

    Hi keep having the following linker errors. Kindly help me out

    --------------------Configuration: ChatServer - Win32 Debug--------------------
    Compiling...
    ChatServer.cpp
    Linking...
    ChatServer.obj : error LNK2001: unresolved external symbol _WSAStartup@8
    ChatServer.obj : error LNK2001: unresolved external symbol "public: static struct CRuntimeClass const CChatServerDoc::classCChatServerDoc" (?classCChatServerDoc@CChatServerDoc@@2UCRuntimeClass@@B)
    ChatServer.obj : error LNK2001: unresolved external symbol "public: static struct CRuntimeClass const CMainFrame::classCMainFrame" (?classCMainFrame@CMainFrame@@2UCRuntimeClass@@B)
    ChatServer.obj : error LNK2001: unresolved external symbol "public: static struct CRuntimeClass const CChatServerView::classCChatServerView" (?classCChatServerView@CChatServerView@@2UCRuntimeClass@@B)
    msvcrtd.lib(crtexe.obj) : error LNK2001: unresolved external symbol _main
    Debug/ChatServer.exe : fatal error LNK1120: 5 unresolved externals
    Error executing link.exe.

    ChatServer.exe - 6 error(s), 0 warning(s)

    Reply
  • How to detect if the client is offline?

    Posted by Legacy on 01/26/2002 12:00am

    Originally posted by: kdh

    Hi,all
    If one client is off line or the power is suddenly turned off,how can the server know that?If you know the answer,please tell me. Thank you very much.

    Reply
  • Loading, Please Wait ...

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

Top White Papers and Webcasts

  • Instead of only managing projects organizations do need to manage value! "Doing the right things" and "doing things right" are the essential ingredients for successful software and systems delivery. Unfortunately, with distributed delivery spanning multiple disciplines, geographies and time zones, many organizations struggle with teams working in silos, broken lines of communication, lack of collaboration, inadequate traceability, and poor project visibility. This often results in organizations "doing the …

  • The impact of a data loss event can be significant. Real-time data is essential to remaining competitive. Many companies can no longer afford to rely on a truck arriving each day to take backup tapes offsite. For most companies, a cloud backup and recovery solution will eliminate, or significantly reduce, IT resources related to the mundane task of backup and allow your resources to be redeployed to more strategic projects. The cloud - can now be comfortable for you – with 100% recovery from anywhere all …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds