Socket Programming Socket Programming References redKlyde’s tutorial set Winsock2

Document Sample
Socket Programming Socket Programming References redKlyde’s tutorial set Winsock2 Powered By Docstoc
					Socket Programming
redKlyde’s tutorial set
Winsock2 for games (
Introduction (javadoc)
      TCP provides a reliable, point-to-point communication
      channel that client-server applications on the Internet
      use to communicate with each other.
      To communicate over TCP, a client program and a
      server program establish a connection to one another.
      Each program binds a socket to its end of the
      connection. To communicate, the client and the
      server each reads from and writes to the socket
      bound to the connection.

Fall 2010                                                 2
     Normally, a server runs on a specific computer and has a socket
     that is bound to a specific port number.
     The server just waits, listening to the socket for a client to make
     a connection request.
     The client knows the hostname of the machine on which the
     server is running and the port number to which the server is
     To make a connection request, the client tries to rendezvous
     with the server on the server's machine and port.

Spring 2005
Fall 2010                                                            3
Client/Server (cont)
      If everything goes well, the server accepts the connection.
      On the client side, if the connection is accepted, a socket is
      successfully created and the client can use the socket to
      communicate with the server. The client and server can now
      communicate by writing to or reading from their sockets.

Fall 2010                                                              4
Socket Definition
      A socket is one endpoint of a two-way
      communication link between two
      programs running on the network. A
      socket is bound to a port number so
      that the TCP layer can identify the
      application that data is destined to be

Fall 2010                                       5
Winsock 2.2
  There are different ways to program with
    the very basic UNIX/Berkeley type functions,
    the Microsoft’s Windows specialized version of
    the basic functions, or
    the Object Orientated MFC version.

Fall 2010                                       6
Learning Objectives
      Creating a socket (and VC setup)
      Making the connection
      Sending and receiving data
      Multiple host connection
           [Optional multi-thread implementation]

      Integrating with game loop

Fall 2010                                            7
redKlyde (Tutorial #1)
      VC setting: add WS2_32.lib        Every winsock function will
      to project                        return SOCKET_ERROR if
      WSAData: hold info about          error occurred
      our network capability            WSAGetLastError() to get
      WSAStartup (…): start up          the errorcode [see msdn for
      winsock                           details]

      mysock = socket (AF_INET,
      SOCK_STREAM,0);                   WSACleanup(): last call of
        creates a TCP socket for
          Internet; fails if too many
          sockets are created
       closesocket (mysock);

Fall 2010                                                            8
 Tutorial 1
              Winsock v2.2

AF_INET: Socket for internet
[SOCK_DGRAM: UDP socket]

  Fall 2010                    9
redKlyde (Toot #2 – Server)
      Host/net byte ordering      Listen (listensock,
      of numbers (next page)      backlog)
      Bind: associate a port to   Clientsocket = accept
      socket to send/receive      (listensock, 0,0)
                                     A blocking call [use
      Socket address                  debugger to verify]
      structure [sockaddr_in]:
      port no., Internet          Backlog: the number of
      protocol, …                 clients you can keep
      Port no: stay above         waiting before calling
      2024                        accept()

Fall 2010                                                    10
      Big endian           Little endian
      Network protocal     windows
      Hton, ntoh
           Host-network

Fall 2010                                  11
hton & ntoh

              Sizeof (short) = 4 bytes
              Sizeof (long) = 8 bytes

              htons (7654) = 58909
              htonl (7654) = 3860660224

Fall 2010                                 12
Bind the socket to port 7654

     Spring 2005
     Fall 2010                 13
redKlyde (Toot#2 – client)
      Which server to        Connect (sock,
      connect to?            sockaddr_in, size)
      “host entry”
      Socket address
      [sockaddr_in]: port,

Fall 2010                                         14
Tut 2(c)

Fall 2010   15
redKlyde (Toot#3)
      Send/recv fixed length message
      Macros for earlier commands
      Nbytes = recv (clientsock, buffer,buffersize,0)
      Nbytes = send (clientsock,buffer,size,0);

Fall 2010                                         16
Tut3 (server)

Spring 2005
Fall 2010       17
Tut3 (client)

Fall 2010       18
redKlyde (Toot#4)
      How about variable         !? Why the size won’t
      length message?            be mixed with the
      TCP concatenates all       coming messages?!
      packets into one big       This is the simple
      chunk                      protocol we set for this
      Use escape character to    example.
      Send the size of
      message first, then recv

Fall 2010                                              19
Tut4 (server)

Fall 2010       20
Tut4 (client)

Fall 2010       21
Tut5: Overview
      Thread: a sequence of instructions that may
      execute in parallel with other threads
      Multi-threaded AP
           Accept thread: accept clients connecting to the
            server socket; add client socket to masterset
           Main thread: polling from selected sets to process
            variable-length input
      Shared memory: FD_SET (set of client

Fall 2010                                                   22
redKlyde (Toot#5 – server)
      Blocking calls: accept,        Select: create a list of
      recv                           sockets that already
      Nonblocking calls: send,       have data to read
      connect, …                     Exception handling:
      FD_SET (file descriptor           Clean disconnect: the
      set): a list of sockets            client closes the socket
                                         and exits [no error]
           Data member: fd_count,
            fd_array                    dropped connection [an
                                         error will occur]
      Macros for FD_SET:                Remove from FD_SET,
           FD_SET (sock, &set)          close the corresponding
           FD_ZERO (&set)               socket
           FD_CLR (sock,&set)
           FD_ISSET(sock,&set)
Fall 2010                                                       23
                            debug multi-threaded
Setting Up

             Mutex: mutual exclusion algorithms used
             in concurrent programming to avoid the
             simultaneous use of a common resource

Fall 2010                                        24

Fall 2010   25

Spring 2005
Fall 2010     26

Error check…

      Fall 2010        27
Error (dropped connection)

Fall 2010                    28
                           Client called
Error (clean disconnect)   closesocket

Fall 2010                              29
Command Summary
      WSAStartup; WSACleanup
       socket(); closesocket();
       bind(); listen(); accept(); gethostbyname(),
       ntohl(), ntohs(), htonl(), htons()
       send(), recv()
Fall 2010                                         30

Shared By: