+ Reply to Thread
Results 1 to 5 of 5

Thread: Cơ chế truyền thông Socket

  1. #1

  2. #2

    Linux Socket Programming In C++

    By Rob Tougher



    Contents

    1. Introduction 2. Overview of Client-Server Communications 3. Implementing a Simple Server and Client 3.1 Server - establishing a listening socket 3.2 Client - connecting to the server 3.3 Server - Accepting the client's connection attempt 3.4 Client and Server - sending and receiving data 4 Compiling and Testing Our Client and Server 4.1 File list 4.2 Compile and test 5. Conclusion 1. Introduction

    Sockets are a mechanism for exchanging data between processes. These processes can either be on the same machine, or on different machines connected via a network. Once a socket connection is established, data can be sent in both directions until one of the endpoints closes the connection.
    I needed to use sockets for a project I was working on, so I developed and refined a few C++ classes to encapsulate the raw socket API calls. Generally, the application requesting the data is called the client, and the application servicing the request is called the server. I created two primary classes, ClientSocket and ServerSocket, that the client and server could use to exchange data.
    The goal of this article is to teach you how to use the ClientSocket and ServerSocket classes in your own applications. We will first briefly discuss client-server communications, and then we will develop a simple example server and client that utilize these two classes.
    2. Overview of Client-Server Communications

    Before we go jumping into code, we should briefly go over the set of steps in a typical client-server connection. The following table outlines these steps:
    Server Client 1. Establish a listening socket and wait for connections from clients. 2. Create a client socket and attempt to connect to server. 3. Accept the client's connection attempt. 4. Send and receive data. 4. Send and receive data. 5. Close the connection. 5. Close the connection. That's basically it. First, the server creates a listening socket, and waits for connection attempts from clients. The client creates a socket on its side, and attempts to connect with the server. The server then accepts the connection, and data exchange can begin. Once all data has been passed through the socket connection, either endpoint can close the connection.
    3. Implementing a Simple Server and Client

    Now its time to dig into the code. In the following section we will create both a client and a server that perform all of the steps outlined above in the overview. We will implement these operations in the order they typically happen - i.e. first we'll create the server portion that listens to the socket, next we'll create the client portion that connects to the server, and so on. All of the code in this section can be found in simple_server_main.cpp and simple_client_main.cpp.
    If you would rather just examine and experiment with the source code yourself, jump to this section. It lists the files in the project, and discusses how to compile and test them. 3.1 Server - establishing a listening socket

    The first thing we need to do is create a simple server that listens for incoming requests from clients. Here is the code required to establish a server socket:
    listing 1 : creating a server socket ( part of simple_server_main.cpp ) #include "ServerSocket.h"
    #include "SocketException.h"
    #include <string>

    int main ( int argc, int argv[] )
    {
    try
    {
    // Create the server socket
    ServerSocket server ( 30000 );


    // rest of code -
    // accept connection, handle request, etc...

    }
    catch ( SocketException& e )
    {
    std::cout << "Exception was caught:" << e.description() << "\nExiting.\n";
    }

    return 0;
    }



    That's all there is to it. The constructor for the ServerSocket class calls the necessary socket APIs to set up the listener socket. It hides the details from you, so all you have to do is create an instance of this class to begin listening on a local port.
    Notice the try/catch block. The ServerSocket and ClientSocket classes use the exception-handling feature of C++. If a class method fails for any reason, it throws an exception of type SocketException, which is defined in SocketException.h. Not handling this exception results in program termination, so it is best to handle it. You can get the text of the error by calling SocketException's description() method as shown above.
    3.2 Client - connecting to the server

    The second step in a typical client-server connection is the client's responsibility - to attempt to connect to the server. This code is similar to the server code you just saw:
    listing 2 : creating a client socket ( part of simple_client_main.cpp ) #include "ClientSocket.h"
    #include "SocketException.h"
    #include <iostream>
    #include <string>

    int main ( int argc, int argv[] )
    {
    try
    {
    // Create the client socket
    ClientSocket client_socket ( "localhost", 30000 );


    // rest of code -
    // send request, retrieve reply, etc...

    }
    catch ( SocketException& e )
    {
    std::cout << "Exception was caught:" << e.description() << "\n";
    }

    return 0;
    }



    By simply creating an instance of the ClientSocket class, you create a linux socket, and connect it to the host and port you pass to the constructor. Like the ServerSocket class, if the constructor fails for any reason, an exception is thrown.
    3.3 Server - accepting the client's connection attempt

    The next step of the client-server connection occurs within the server. It is the responsibility of the server to accept the client's connection attempt, which opens up a channel of communication between the two socket endpoints.
    We have to add this functionality to our simple server. Here is the updated version:
    listing 3 : accepting a client connection ( part of simple_server_main.cpp ) #include "ServerSocket.h"
    #include "SocketException.h"
    #include <string>

    int main ( int argc, int argv[] )
    {
    try
    {
    // Create the socket
    ServerSocket server ( 30000 );

    while ( true )
    {
    ServerSocket new_sock;
    server.accept ( new_sock );


    // rest of code -
    // read request, send reply, etc...

    }
    }
    catch ( SocketException& e )
    {
    std::cout << "Exception was caught:" << e.description() << "\nExiting.\n";
    }

    return 0;
    }


    Accepting a connection just requires a call to the accept method. This method accepts the connection attempt, and fills new_sock with the socket information about the connection. We'll see how new_sock is used in the next section.
    3.4 Client and Server - sending and receiving data

    Now that the server has accepted the client's connection request, it is time to send data back and forth over the socket connection.
    An advanced feature of C++ is the ability to overload operators - or simply, to make an operator perform a certain operation. In the ClientSocket and ServerSocket classes I overloaded the << and >> operators, so that when used, they wrote data to and read data from the socket. Here is the updated version of the simple server:
    listing 4 : a simple implementation of a server ( simple_server_main.cpp ) #include "ServerSocket.h"
    #include "SocketException.h"
    #include <string>

    int main ( int argc, int argv[] )
    {
    try
    {
    // Create the socket
    ServerSocket server ( 30000 );

    while ( true )
    {

    ServerSocket new_sock;
    server.accept ( new_sock );

    try
    {
    while ( true )
    {
    std::string data;
    new_sock >> data;
    new_sock << data;
    }
    }
    catch ( SocketException& ) {}

    }
    }
    catch ( SocketException& e )
    {
    std::cout << "Exception was caught:" << e.description() << "\nExiting.\n";
    }

    return 0;
    }


    The new_sock variable contains all of our socket information, so we use it to exchange data with the client. The line "new_sock >> data;" should be read as "read data from new_sock, and place that data in our string variable 'data'." Similarly, the next line sends the data in 'data' back through the socket to the client.
    If you're paying attention, you'll notice that what we've created here is an echo server. Every piece of data that gets sent from the client to the server gets sent back to the client as is. We can write the client so that it sends a piece of data, and then prints out the server's response:
    listing 5 : a simple implementation of a client ( simple_client_main.cpp ) #include "ClientSocket.h"
    #include "SocketException.h"
    #include <iostream>
    #include <string>

    int main ( int argc, int argv[] )
    {
    try
    {

    ClientSocket client_socket ( "localhost", 30000 );

    std::string reply;
    try
    {
    client_socket << "Test message.";
    client_socket >> reply;
    }
    catch ( SocketException& ) {}

    std::cout << "We received this response from the server:\n\"" << reply << "\"\n";;

    }
    catch ( SocketException& e )
    {
    std::cout << "Exception was caught:" << e.description() << "\n";
    }

    return 0;
    }

    We send the string "Test Message." to the server, read the response from the server, and print out the response to std output.
    4. Compiling and Testing Our Client And Server

    Now that we've gone over the basic usage of the ClientSocket and ServerSocket classes, we can build the whole project and test it.
    4.1 File list

    The following files make up our example:
    Miscellaneous: Makefile - the Makefile for this project Socket.h, Socket.cpp - the Socket class, which implements the raw socket API calls. SocketException.h - the SocketException class Server: simple_server_main.cpp - main file ServerSocket.h, ServerSocket.cpp - the ServerSocket class Client: simple_client_main.cpp - main file ClientSocket.h, ClientSocket.cpp - the ClientSocket class 4.2 Compile and Test

    Compiling is simple. First save all of the project files into one subdirectory, then type the following at your command prompt:
    prompt$ cd directory_you_just_created
    prompt$ make


    This will compile all of the files in the project, and create the simple_server and simple_client output files. To test these two output files, run the server in one command prompt, and then run the client in another command prompt:
    first prompt:
    prompt$ ./simple_server
    running....




    second prompt:
    prompt$ ./simple_client
    We received this response from the server:
    "Test message."

    prompt$

    The client will send data to the server, read the response, and print out the response to std output as shown above. You can run the client as many times as you want - the server will respond to each request.
    5. Conclusion

    Sockets are a simple and efficient way to send data between processes. In this article we've gone over socket communications, and developed an example server and client. You should now be able to add socket communications to your applications!

  3. #3



    C & LINUX SOCKET: README FIRST


    Well, here is another TCP/IP network programming but here we are using GNU C on Linux/Fedora Core platform. This tutorial provides quite a complete discussion presented in graphically manner with working program examples from the very basic networking up to the packet level. You need to have some knowledge and skill in C programming language and also familiar with Linux/Fedora Core platform in order to have a good start.
    The program examples given include the client and server codes but you can test the client and server codes at the same computer. Don't worry about the GNU C, it still based on the Standard C (ISO/IEC). The compiler used is GCC (GNU Compiler
    Collection) and run on the Linux/Fedora Core 3 platform. You can find the how-to compile using GCC and G++ (for C++) in GCC & G++ 1 and GCC & G++ 2. The GDB (GNU Debugger) debugger how-to also included. Tenouk need to learn the Linux socket because of the knowledge that needed in order to learn and understand the buffer overflow problem when doing the C and C++ coding.
    C and Linux Socket Topics


    Each topic provide notes and working program examples, from the fundamentals up to the four TCP/IP stacks. Packet level programming that cover the TCP, UDP, IP and other dominant protocols also included. Those code examples have been run on server and client machine to demonstrate the functionalities through the program output. Topics have been arranged in a proper learning curve.

  4. #4

    Internetworking with TCP/IP, Vol. III: Client-Server Programming and Applications--BSD Socket Version (2nd Edition)



    By Douglas E. Comer, David L. Stevens,

    Publisher: Prentice Hall
    Number Of Pages: 552
    Publication Date: 1996-03-25
    Sales Rank: 326192
    ISBN / ASIN: 013260969X
    EAN: 9780132609692
    Binding: Paperback
    Manufacturer: Prentice Hall
    Studio: Prentice Hall
    Average Rating: 5

    This is a revised version of this volume. Changes in this edition include: Code has been updated to use ANSI C and the UNIX operating systems (POSIX). Covers SLIP connections (a popular program that allows TCP/IP access to the Internet over dial-up phone systems. Latest changes in Network File System protocol (NFS3). This edition focuses on the BSD version of UNIX. This volume answers the question ��How does one use TCP/IP?�� �� focusing on the client-server paradigm, and examining algorithms for both the client and server components of a distributed program. Describes the AT&T TLI interface and uses it in all examples. The principles underlying distributed programs and all server designs are emphasized. Thoroughly covers the many ways to design interactive and concurrent client and server software, as well as their proper use and application. Concepts apply to Client-Server programs in general; not just TCP/IP. Any communications professional who wants to put TCP/IP to use. This is everyone working on Internet communications.

    Review:
    An excellent book with well explained working examples
    I have to hand it to Mr. Comer and Stevens, they have done an excellent job writing a book that explains everything clearly with very well defined (and actually working) examples.
    If you are interested in learning TCP/IP programming on Unix platform this is the only book you need.
    It does assume that you have knowledge of some C programming, but it does not assume that you are an expert.
    Excellent Book.


    Review:
    Like Cliff Notes
    This is a great book and I see why some teachers chose it for grad students. I didn't do well in networks last semester because I had to learn BSD TCP/IP sockets from sources like book snippets my teacher gave me, man pages, and various Internet sources. The textbook I had to buy for class has almost no C code or any explanations about BSD sockets. So, I invested into this and the Richard Stevens (UNIX Network Programming) book. Both are excellent assests.
    Pro (This book): I like how it explained what each important function did (like read/write)
    Con: The example code could be a little better.
    This book is well-written and will be a good reference once I'm through with my class. I bought all 3 volumes since I could get them at a great price. What especially helped: sometimes books would take up to 50 pages explaining a topic. The "Internetworking with TCP/IP" series are excellent at giving the bottom line and at times makes it easier to understand the details within the longer-winded pages of other books. In a way, to me, it's like a set of cliff notes to my textbook.
    If you're baffled about network programming, these books might be worth a try.


    Review:
    A Perfect Text
    I have been using Internetworking with TCP/IP Volume III for almost ten years now to teach a graduate course on client server programming. I think it is perhaps the most perfect textbook ever written. Comer's code is exquisite and can be used to teach clear and efficient coding in C. His explanations are perfect. He says everything that needs to be said, and no more. His presentation about the foundation of all distributed computing is clear concise and on target. Students require some reminders about the fact that this book can't be read like a novel, or like any less competent textbook. They need to read and carefully consider each line. Comer includes everything that is needed in the book and its appendices. In every case, you see very careful and concise statements of how things really work. I just reread his chapter on NFS this morning and was reminded about how he can take the complex and invisible and make it completely understandable.
    Professor Comer's books are wonderful, but his contributions don't stop there. If you pride yourself on writing and are new to the academic realm you might find it useful to go to his website and read his advice on writing a dissertation. If you are a PhD student, or a master's student writing a thesis, this should be a mandatory stop. If you are simply a person who takes pride in writing clearly, you will learn important things.


    Review:
    A good,readable,working guide to TCP/IP Socket
    I used this book from cover to cover in a Unix Socket Programming class. A few good points about this book: 1) The sample do compiled on Linux with no problems. That's a plus. 2) The author emphasized good client-server design principles. 3) The introduction is gentle and very readble. 4) The code sample is directly,simple and not riddled with unnecessary details to "show off" like some authors do.
    You don't need much Unix to do exercise in this book.About the only System calls you need to know are fork(),Select(),sigalarm() and execve(). The book could have been expanded to cover HTTP,SOAP and some other protocols to give it a 5stars.

  5. #5

+ Reply to Thread

Similar Threads

  1. Tìm chổ sửa socket
    By haok5d in forum Tổng hợp các thiết bị khác ...
    Replies: 0
    Last Post: 09-23-2009, 04:39 AM
  2. Gãy chân socket.Muốn tìm chổ sửa.
    By hthanhh2006 in forum Tổng hợp các thiết bị khác ...
    Replies: 0
    Last Post: 09-23-2009, 03:48 AM
  3. Replies: 0
    Last Post: 09-20-2009, 05:03 PM
  4. HCM Cần mua AMD socket 939 x2 hoặc AMD FX Socket 939!!
    By adachi00 in forum Nhà kho tổng hợp
    Replies: 0
    Last Post: 08-30-2008, 04:26 AM
  5. Replies: 7
    Last Post: 09-14-2007, 02:39 PM

Visitors found this page by searching for:

Nobody landed on this page from a search engine, yet!

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts