Title: Socket Programming
1Socket Programming
- CS 204 Advanced Programming
- Erkay Savas
- Expanded by Berrin Yanikoglu (2nd half)
2Client/Server Architecture
ftp server
telnet server
web server
- Client has to know the servers addressand port
number initially not vice versa.
3A TCP/IP Network
application
TCP
IP
(e.g. Ethernet)
Router
4Communication Protocols
Application protocol
Web client
Web server
HTTP
5TSP vs IP
- The Transmission Control Protocol (TCP) is one of
the core protocols of the Internet protocol
suite, often simply referred to as TCP/IP. Using
TCP, applications on networked hosts can create
connections to one another, over which they can
exchange streams of data using Stream Sockets.
The protocol guarantees reliable and in-order
delivery of data from sender to receiver. TCP
also distinguishes data for multiple connections
by concurrent applications (e.g., Web server and
e-mail server) running on the same host. - TCP supports many of the Internet's most popular
application protocols and resulting applications,
including the World Wide Web, e-mail, File
Transfer Protocol and Secure Shell. - In the Internet protocol suite, TCP is the
intermediate layer between the Internet Protocol
(IP) below it, and an application above it.
Applications often need reliable pipe-like
connections to each other, whereas the Internet
Protocol does not provide such streams, but
rather only best effort delivery (i.e.,
unreliable packets). TCP does the task of the
transport layer in the simplified OSI model of
computer networks. The other main transport-level
Internet protocol is UDP. - Applications send streams of octets (8-bit bytes)
to TCP for delivery through the network, and TCP
divides the byte stream into appropriately sized
segments. TCP then passes the resulting packets
to the Internet Protocol, for delivery through a
network to the TCP module of the entity at the
other end. - TCP checks to make sure that no packets are lost
by giving each packet a sequence number, which is
also used to make sure that the data are
delivered to the entity at the other end in the
correct order. The TCP module at the far end
sends back an acknowledgement for packets which
have been successfully received a timer at the
sending TCP will cause a timeout if an
acknowledgement is not received within a
reasonable round-trip time (or RTT), and the
(presumably lost) data will then be
re-transmitted. The TCP checks that no bytes are
damaged by using a checksum one is computed at
the sender for each block of data before it is
sent, and checked at the receiver.
6Alternatives to TCP
- For many applications TCP is not appropriate. One
big problem is that the application cannot get at
the packets coming after a lost packet until the
retransmitted copy of the lost packet is
received. This causes problems for real-time
applications such as streaming multimedia (such
as Internet radio) and voice over IP (VoIP) where
it is sometimes more useful to get most of the
data in a timely fashion than it is to get all of
the data in order. - Generally where TCP is unsuitable the User
Datagram Protocol (UDP) is used. This provides
the application multiplexing and checksums that
TCP does, but does not handle building streams or
retransmission, giving the application developer
the ability to code those in a way suitable for
the situation and/or to replace them with other
methods like forward error correction or
interpolation.
7What is a Socket?
- A mechanism through which an application may send
and receive data. - Two processes can communicate by creating sockets
and sending messages through sockets - Information written to a socket by an application
on one machine can be read by an application on
another machine, and vice versa. - Two flavors
- stream sockets (uses TCP is reliable)
- datagram sockets (uses UDP)
- Sockets are an interface between application
programs and network protocols
8Socket API (1)
TCP ports
IP
9Creating a Socket
- Defining a socket
- int mySocket // a socket descriptor
- SOCKET mySocket // using SOCKET type of
winsock.h - Creating a socket
int socket(int protocolFamily,int type,int
protocol)
- First parameter usually PF_INET
- Second parameter socket type
- SOCK_STREAM (TCP)
- SOCK_DGRAM (UDP)
- Third parameter end-to-end protocol.
- Use constants IPPROTO_TCP or IPPROTO_UDP
mySocket socket(PF_INET, SOCK_STREAM,
IPPROTO_TCP)
10mySocket socket(PF_INET, SOCK_STREAM,
IPPROTO_TCP)
int socket(int protocolFamily, int type, int
protocol)
- return value is an integer.
- A nonnegative value mean success and can be used
as a handle (similar to file descriptor) - (-1) indicates a failure
- Closing a socket
int close(int socket) //for UNIX int
closesocket(SOCKET socket) //for Windows
- the parameter is the socket descriptor obtained
as return value of a successful socket creation
operation - (0) means success, (-1) indicates a failure
closesocket(mySocket)
11Socket API
- Sockets API provides a generic interface for a
large number of protocol families. - The wildcard PF_INET specifies a socket that uses
protocols from the Internet protocol family. - The wildcard AF_INET specifies a socket that uses
addresses from the Internet protocol family.
12Socket Addressing
- When a socket is first created, it has an
associated protocol but no IP address or port
number - A socket descriptor is used by the application to
identify a socket (similar to a file descriptor) - So it can be closed later
- A socket is later bound to an address and a port
number - Otherwise it cannot send/receive messages
13Addresses
- Needed to locate applications running on other
machines - Two pieces of address in TCP/IP
- Internet (or IP) address
- 32-bit binary number (Four 8-bits number)
- dotted-quad notation (e.g. 10.1.2.3)
- refer to a connection (thus, a host can have more
than one IP address) - Port number
- 16-bit unsigned numbers (1 to 65535)
- used by UDP and TCP
14Specifying Addresses
- Applications using sockets need to specify
Internet addresses and port numbers to the kernel
(OS). - A client must specify the address of a server
application with which it needs to communicate. - The sockets API defines a generic data type for
specifying addresses associated with sockets
struct sockaddr / Structure used by kernel to
store most addresses / unsigned short
sa_family / Address family (AF_INET)/ char
sa_data14 / Family-specific address
/ /
information /
15Address Structure Details
struct sockaddr_in /socket address
internet style / unsigned short sin_family
/ Address family (AF_INET)/ unsigned short
sin_port / Address port (16 bits) / struct
in_addr sin_addr / Internet Addr (32 bits
/ char sin_zero8 / Not
used/ struct in_addr unsigned long s_addr
16Windows Sockets Client Example 1
- Example
- //Create a socket
- SOCKET theSocket socket (PF_INET,
SOCK_STREAM,
IPPROTO_TCP) - SOCKADDR_IN saServer
- saServer.sin_family AF_INET
- //retrieve host information corresponding to
host name string - LPHOSTENT lpHostEntry gethostbyname(serverName)
- //set the Servers address and port
- saServer.sin_addr.s_addr ((LPIN_ADDR)lpHostEn
try-gth_addr_list) -
- //convert 32-bit values between host and
network byte order - saServer.sin_port htons(nPort)
17Details 1/2
- gethostbyname retrieves host information
corresponding to a host name string from a host
database. - Note  The gethostbyname function has been
deprecated by the introduction of the getaddrinfo
function. - inet_addr If no error occurs, inet_addr returns
an unsigned long value containing a suitable
binary representation of the Internet address
given. - Declared in Winsock2.h.winsock2.h
- If the string in the cp parameter does not
contain a legitimate Internet address, for
example if a portion of an "a.b.c.d" address
exceeds 255, then inet_addr returns the value
INADDR_NONE. - unsigned long inet_addr( const char cp )
18Getting the Host Address
- The getaddrinfo function provides
protocol-independent translation from host name
to address. - Prototype
- int getaddrinfo( const char nodename, const
char servname, const
struct addrinfo hints, struct addrinfo res) - Parameters
- nodename Pointer to a null-terminated string
containing a host (node) name or a numeric host
address string. The numeric host address string
is a dotted-decimal IPv4 address or an IPv6 hex
address. - servname Pointer to a null-terminated string
containing either a service name or port number. - hints Pointer to an addrinfo structure that
provides hints about the type of socket the
caller supports. -
- res out Pointer to a linked list of one or
more addrinfo structures containing response
information about the host. - Â
19Details 2/2
- htons do the appropriate conversion for byte
order - Little Endian (Little End In) the lower end
(bytes) are stored first in memory - the Hex value 0x1234 is stored in memory as (0x34
0x12). - the Hex value 0x12345678 would be stored as (0x78
0x56 0x34 0x12). - BigEnd In" does this in the reverse fashion
- 0x1234 is stored as (0x12 0x34) in memory.
- This is the method used by Motorola computers and
can also be used on RISC-based computers.
20- You can also specify a given IP number directly
- sockaddr_in sa
- sa.sin_familyAF_INET
- Sa.sin_addr.s_un.s_un_b.s_b1 192
- Sa.sin_addr.s_un.s_un_b.s_b2 255
- Sa.sin_addr.s_un.s_un_b.s_b3 100
- Sa.sin_addr.s_un.s_un_b.s_b4 4
- struct in_addr
- union struct u_char s_b1,s_b2,s_b3,s_b4
S_un_b - struct u_short s_w1,s_w2 S_un_w
- u_long S_addr
- S_un
-
- define s_addr S_un.S_addr
-
- struct sockaddr_in
21Client
22TCP Client
- A typical TCP client goes through four basic
steps - Create a TCP socket using socket().
- Establish a connection to the server using
connect(). - Communicate using send() and recv().
- Close the connection with close().
23Functions for TCP Client - 1/2
int socket(int protocolFamily, int type, int
protocol)
int connect(int socket, struct sockaddr
serverAddress, unsigned int addressLength)
- Parameters
- First parameterthe descriptor obtained as a
return value of a successful socket creation
operation - Second parameter the address of the server (the
struct data type must appropriately filled by the
server address) - Third parameter always use sizeof(sockaddr).
24What Happens After Connect
socket()
connect()
When a socket is first created, queues
(illustrated above) are closed. During connect,
local port and local IP address is assigned to
it, as well as the remote IP/port.
25Functions for TCP Client - 2/2
int send(int socket, constant void msg, unsigned
int msgLength, int flags) int recv(int socket,
void rcvBuffer, unsigned int bufferLength, int
flags)
- Default behavior for send() is to block until all
of the data is sent - Default behavior for recv() is to block until at
least some bytes are received. - flags (default 0) provides a way to change the
default behavior
26Server
27TCP Server
- Four steps of constructing a TCP server
- Create a TCP socket using socket().
- Assign a (local) port number to the socket with
bind(). - Tell the system to allow connections to be made
to that port, using listen(). - Repeatedly do the following
- Call accept() to get a new socket for each client
connection - Communicate with the client via that new socket
using send() and recv().
28Bind
- int bind(int socket, struct sockaddr
localAddress, unsigned int
addressLength)
- First parameter the descriptor returned by an
earlier call to socket(). - Second parameter a pointer to a sockaddr. For
TCP/IP applications, it will actually point to a
sockaddr_in containing IP address of the server
and a port number to listen on - Third parameter use sizeof(sockaddr_in)
- Return value 0 for success 1 for failure
29Windows Sockets Server Example 1(code demoed
in class)
-
- SOCKET listenSocket
- listenSocket socket (PF_INET, // Address
family - SOCK_STREAM, // Socket type
- IPPROTO_TCP) // Protocol
- ...
- SOCKADDR_IN saServer
- saServer.sin_family AF_INET
- saServer.sin_addr.s_addr INADDR_ANY // Let
WinSock supply address - saServer.sin_port htons(nPort) // Use port
from command line -
- // bind the name to the socket
- int nRet bind (listenSocket, // Socket
- (LPSOCKADDR)saServer, // Our
address - sizeof(struct sockaddr)) // Size of address
structure
30Listen
int listen(int socket, int queueLimit)
- Incoming TCP connection requests will be handled
and then queued for acceptance by the program - The queueLimit specifies an upper bound on the
number of incoming connections that can be
waiting at any time - The current socket is only used for listening to
incoming connections and it is not used for
sending and receiving actual data.
31Server Side Under the Hood
socket()
bind()
listen()
32Accept
int accept(int socket, struct sockaddr
clientAddress, unsigned int
addressLength)
- It removes one connection request from the queue.
-
- If no pending connections are present on the
queue and the socket is not marked as
non-blocking, accept() blocks until a connection
is present. - If the socket is marked as non-blocking and no
pending connections are present on the queue,
accept() returns an error. - When successful, accept()
- creates a new socket with the same properties of
socket, and returns a new handle to the socket - fills in the sockaddr structure pointed by the
clientAddress. - returns a descriptor for a new socket that is
connected to the client - The accepted socket is used to read and write
data to and from the socket that connected to it. - The original socket is returned to the listening
state.
33Windows Sockets Server Example 2
-
- nRet listen (listenSocket, // Start listening
to this socket - SOMAXCONN) // Number of
connection request queue - ...
- SOCKET remoteSocket
- remoteSocket accept (listenSocket, //
Listening socket - NULL, // Optional client address
- NULL)
- ...
34Server Side Under the Hood
listen()
accept()
35Client/Server Interaction
36TCP Server vs. TCP Client
- Creating the socket, sending, receiving, and
closing are the same in both party. - The differences
- The server binds an address to the socket
- By calling bind() function
- We say that the server listens to this address
- i.e. underlying TCP protocol implementation waits
for connections from clients by calling listen()
on the socket - The server accepts the connection request
- It gets a new socket for the incoming connection
by calling accept().
37Review
- Steps of a TCP Server
- socket() - Get a socket
- bind() - bind to the socket
- listen() - listen for traffic on the socket
- accept() - accept incoming connections on the
socket - recv() - receive incoming traffic
- send() - send traffic to connection
-
- Steps of a TCP Client
- socket() - Get a socket
- connect() - Connect to a server
- send() - send traffic to server
- recv() - receive traffic from server
38Windows Sockets
- Windows Sockets are based on the UNIX sockets
implementation in the Berkeley Software
Distribution (BSD, release 4.3) - Two socket types are available
- Stream sockets provide for a data flow without
record boundaries a stream of bytes. Streams
are guaranteed to be delivered and to be
correctly sequenced and unduplicated. - Datagram sockets support a record-oriented data
flow that is not guaranteed to be delivered and
may not be sequenced as sent or unduplicated. - Sequenced means that packets are delivered in
the order sent. - Unduplicated means that you get a particular
packet only once.
39Windows Sockets
- Both kinds of sockets are bi-directional they
are data flows that can be communicated in both
directions simultaneously (full-duplex). - The network transport layer may break up or group
data into packets of reasonable size.
40Windows Sockets Client Example 1
- Example
- //Create a socket
- SOCKET theSocket socket (PF_INET,
SOCK_STREAM,
IPPROTO_TCP) - SOCKADDR_IN saServer
- saServer.sin_family AF_INET
- //retrieve host information corresponding to
host name string - LPHOSTENT lpHostEntry gethostbyname(serverName)
- //set the Servers address and port
- saServer.sin_addr.s_addr ((LPIN_ADDR)lpHostEn
try-gth_addr_list) -
- //convert 32-bit values between host and
network byte order - saServer.sin_port htons(nPort)
41Windows Sockets Client Example
- ...
- nRet connect (theSocket,
- (LPSOCKADDR)saServer, // Server address
- sizeof(struct sockaddr)) // Length
of server address structure - ...
- ...
42Windows Sockets Client Example
- printf("Enter the data to be sent to the
server(up to 256 bytes)\n") - gets(szBuf)
- nRet send (theSocket, // Connected socket
- szBuf, // Data buffer
- strlen(szBuf), // Length of data
- 0) // Flags
- ...
- nRet recv (theSocket, // Connected client
- szBuf, // Receive buffer
- sizeof(szBuf), // Max length of
buffer - 0) // Flags
- ...
- closesocket(theSocket)
43Windows Sockets Server Example 1(code demoed
in class)
-
- SOCKET listenSocket
- listenSocket socket (AF_INET, // Address
family - SOCK_STREAM, // Socket type
- IPPROTO_TCP) // Protocol
- ...
- SOCKADDR_IN saServer
- saServer.sin_family AF_INET
- saServer.sin_addr.s_addr INADDR_ANY // Let
WinSock supply address - saServer.sin_port htons(nPort) // Use port
from command line -
- // bind the name to the socket
- int nRet bind (listenSocket, // Socket
- (LPSOCKADDR)saServer, // Our
address - sizeof(struct sockaddr)) // Size of address
structure
44Windows Sockets Server Example 2
-
- nRet listen (listenSocket, // Start listening
to this socket - SOMAXCONN) // Number of
connection request queue - ...
- SOCKET remoteSocket
- remoteSocket accept (listenSocket, //
Listening socket - NULL, // Optional client address
- NULL)
- ...
45Windows Sockets Server Example 3
-
- nRet recv (remoteSocket, // Connected client
- szBuf, // Receive buffer
- sizeof(szBuf), // Length of buffer
- 0) // Flags
- ...
- nRet send (remoteSocket, // Connected socket
- szBuf, // Data buffer
- strlen(szBuf), // Length of data
- 0) // Flags
- ...
- closesocket(remoteSocket)
- closesocket(listenSocket)
46Winsock DLL
- The WSAStartup function must be the first Windows
Sockets function called by an application or DLL.
- WORD wVersionRequested MAKEWORD(1,1)
- //include winsock.h if higher versions, may
need winsock2.h - WSADATA wsaData
- int nRet
-
- // Initialize WinSock and check version
- nRet WSAStartup(wVersionRequested, wsaData)
- if (wsaData.wVersion ! wVersionRequested)
-
- fprintf(stderr,"\n Wrong version\n")
- return
-
- Complete info (latest versions etc)
- http//msdn2.microsoft.com/en-us/library/ms742213.
aspx
47Winsock DLL
- The WSACleanup function terminates use of the
Winsock 2 DLL (Ws2_32.dll). - Sockets that were open when WSACleanup was called
are reset and automatically deallocated as if
closesocket were called. - //Release Winsock DLL
- WSACleanup()
-
- Complete info (latest versions etc)
- http//msdn2.microsoft.com/en-us/library/ms741549.
aspx
48- You will need to check the documentation to find
more details.
49UNIX Examples
50UNIX example TCPEchoClient.c - 1/4
- include ltstdio.hgt / for printf()
/include ltsys/socket.hgt / for
socket(), connect(), send()
and recv() / include
ltarpa/inet.hgt / for sockaddr_in and inet_addr()
/include ltstdlib.hgt / for atoi()
/include ltstring.hgt / for
memset() /include
ltunistd.hgt / for close()
/ - define RCVBUFSIZE 32 / Size of receive buffer
/ - void DieWithError(char errorMessage) / error
handling function / - int main(int argc, char argv)
- int sock struct sockaddr_in echoServAddr
unsigned short echoServPort char servIP
...
51TCPEchoClient.c - 2/4
- ...int main(int argc, char argv) ...
- char echoString char echoBufferRCVBUFSIZE
unsigned int echoStringLen int bytesRcvd,
totalBytesRcvd - if (argc ! 2)) printf(Usage s
ltServer IPgt ltEcho Wordgt \n, argv0)
exit(1) - servIP argv1 echoString argv2
echoServPort 7 / well-known port for echo
service / ...
52TCPEchoClient.c - 3/4
- ... / Create a reliable, stream socket using
TCP / if(sock socket(PF_INET, SOCK_STREAM,
IPPROTO_TCP)) lt 0) DieWithError(socket()
failed) - / Construct the server address structure /
memset(echoServAddr, 0, sizeof(echoServAddr)
echoServAddr.sin_family AF_INET / Convert
Servers IP address string to proper IP address
/ - echoServAddr.sin_addr.s_addr
inet_addr(ServIP) - / Convert the port num to proper order /
- echoServAddr.sin_port htons(echoServPort)
- / Establish a connection to the echo server
/ if(connect(sock, (struct sockaddr )
echoServAddr, sizeof(echoServAddr)) lt 0)
DieWithError(socket() failed) - echoStringLen strlen(echoString) /Determine
the input length / - ...
53TCPEchoClient.c - 4/4
- ... / Send the string to the server /
if(send(sock, echoString, echoStringLen, 0)) !
echoStringLen) DieWithError(send()
failed) - / receive the same string back from the server
/ totalBytesRcvd 0 printf(Received )
while (totalBytesRcvd lt echoStringLen)
if(bytesRcvd recv(sock, echoBuffer, RCVBUFSIZE
- 1, 0)) lt 0) DieWithError(socket()
failed) - totalBytesRcvd bytesRcvd
echobufferbytesRcvd \0
printf(echoBuffer) - prinft(\n) close(sock) exit(0)
54TCPEchoServer.c 1/4
- include ltstdio.hgt / for printf() and
fprintf() /include ltsys/socket.hgt / for
socket(), connect(), send()
and recv() / include
ltarpa/inet.hgt / for sockaddr_in and inet_addr()
/include ltstdlib.hgt / for atoi()
/include ltstring.hgt / for
memset() /include
ltunistd.hgt / for close()
/ - define MAXPENDING 5 / Maximum outstanding
conn. requests / - void DieWithError(char errorMessage) / error
handling func. /void HandleTCPclient(int
clntSocket) / for TCP client handling
function / - int main(int argc, char argv)
- int ServSock, clntSock
- struct sockaddr_in echoServAddr
- struct sockaddr_in echoClntAddr
- unsigned short echoServPort unsigned int
clntLen / Length of client address data
structure
/ ...
55TCPEchoServer.c 2/4
- ...int main(int argc, char argv) ...
- echoServPort 7 / well-known port for echo
service / - / Create socket for incoming connections /
if((servSock socket(PF_INET, SOCK_STREAM,
IPPROTO_TCP)) lt 0) DieWithError(socket()
failed) - / Construct Local address structure /
memset(echoServAddr, 0, sizeof(echoServAddr)
echoServAddr.sin_family AF_INET
echoServAddr.sin_addr.s_addr htonl(INADDR_ANY)
echoServAddr.sin_port htons(echoServPort)
...
56TCPEchoServer.c 3/4
- ...int main(int argc, char argv) ...
- / Bind to the local address /
if(bind(servSock, (sturct sockaddr )
echoServAddr, sizeof(echoServAddr)) lt 0)
DieWithError(bind() failed) - / Mark the socket so it will listen for
incoming connections / if(listen(servSock,
MAXPENDING) lt 0) DieWithError(listen()
failed) ...
57TCPEchoServer.c 4/4
- ...int main(int argc, char argv) ...
- for()
- / Wait for a client to connect /
if((clntSock accept(servSock, (struct
sockaddr ) echoClntAddr, sizeof(echoClntAddr))
lt 0) DieWithError(bind() failed) - / clntSock is connected to a client /
- printf(Handling client s\n,
inet_toa(echoClntAddr.sin_addr)) - HandleTCP(clntSock) / NOT
REACHED /
58HandleTCPClient.c 1/2
- include ltstdio.hgt / for printf() and
fprintf() /include ltsys/socket.hgt / for
send() and recv() / include
ltunistd.hgt / for close()
/ - define RCVBUFSIZE 32
- void DieWithError(char errorMessage) / error
handling func. / - void HandleTCPclient(int clntSocket)
- char echoBufferRCVBUFSIZE int
recvMsgSize - / Receive message from client /
if((recvMsgSizerecv(clntSocket, echoBuffer,
RCVBUFSIZE, 0)) lt 0) DieWithError(recv()
failed) - ...
59HandleTCPClient.c 2/2
- ...
- / Send received string and receive again until
the end of transmission /
while(recvMsgSize gt 0) / zero indicates end of
transmission / - / Echo message back to client /
if(send(clntSock, echoBuffer, recvMsgSize, 0)) !
recvMsgSize) DieWithError(send()
failed) - / Receive message from client /
if((recvMsgSizerecv(clntSock, echoBuffer,
RCVBUFSIZE, 0)) lt 0) DieWithError(recv()
failed) -
- close(clntSocket)
-
60CSockets
61MFC CSockets
- Class based on Windows Sockets
- CSocket mysocket
- Main gain is that CSockets allows you to use
CArchive to send/receive Serializable objects,
without converting them into a byte string. - e.g. a rectangle shape object is sent
automatically (not first sending the top-left
point coordinates, then ...)
62Csocket Class
63Csocket Class
- A CArchive object manages a buffer. When the
buffer of a storing (sending) archive is full, an
associated CFile object writes out the buffer's
contents. - Flushing the buffer of an archive attached to a
socket is equivalent to sending a message. When
the buffer of a loading (receiving) archive is
full, the CFile object stops reading until the
buffer is available again. - Class CSocketFile derives from CFile, but it does
not support CFile member functions (Seek,
GetLength, ...). - All the CSocketFile object must do is write or
read sequences of bytes to or from the associated
CSocket object. Because a file is not involved,
operations such as Seek and GetPosition make no
sense. - CSocketFile is derived from CFile, so it would
normally inherit all of these member functions.
To prevent this, the unsupported CFile member
functions are overridden in CSocketFile to throw
a CNotSupportedException. - The CSocketFile object calls member functions of
its CSocket object to send or receive data.
64Csocket Class http//msdn.microsoft.com/library/d
efault.asp?url/library/en-us/vccore98/HTML/_core_
windows_sockets.3a_.sequence_of_operations.asphtt
p//msdn.microsoft.com/library/default.asp?url/li
brary/en-us/vccore/html/_core_Windows_Sockets_in_M
FC.asp
- SERVER
- // construct a socket
- CSocket sockSrvr
- // bind to the port
- sockSrvr.Create(nPort)1,2
- // start listening
- sockSrvr.Listen( )
- -------
- CLIENT
- // construct a socket
- CSocket sockClient
- // create the SOCKET
- sockClient.Create( )2
- -------
- // seek a connection
- sockClient.Connect(svrAddr,nPort)3,4
same
65Csocket Class
- SERVER ctd.
- ...
- // construct a new, empty socket
- CSocket sockRecv
- // accept connection
- sockSrvr.Accept(sockRecv) 5
- // construct file object
- CSocketFile file(sockRecv)
- CLIENT ctd.
- -------
- // construct file object
- CSocketFile file(sockClient)
66Csocket Class
- SERVER OR CLIENT
- // construct an archive
- CArchive arIn (file,CArchiveload) or
- CArchive arOut (file,CArchivestore)
- // use the archive to pass data
- arIn gtgt dwValue or
- arOut ltlt dwValue6
67Footnotes for the Previous Slides
- 1. Where nPort is a port number.
- 2. The server must always specify a port so
clients can connect. The Create call sometimes
also specifies an address. On the client side,
use the default parameters, which ask MFC to use
any available port. - 3. Where nPort is a port number and strAddr is a
machine address or an Internet Protocol (IP)
address. - 4. Machine addresses can take several forms
ftp.microsoft.com, ucsd.edu. IP addresses use
the dotted number form 127.54.67.32. The
Connect function checks to see if the address is
a dotted number (although it doesnt check to
ensure the number is a valid machine on the
network). If not, Connect assumes a machine name
of one of the other forms. - 5. When you call Accept on the server side, you
pass a reference to a new socket object. You must
construct this object first, but do not call
Create for it. Keep in mind that if this socket
object goes out of scope, the connection closes.
MFC connects the new object to a SOCKET handle.
You can construct the socket on the stack, as
shown, or on the heap. - 6. The archive and the socket file are closed
when they go out of scope. The socket objects
destructor also calls the Close member function
for the socket object when the object goes out of
scope or is deleted.
68CSocket.Create()
- BOOL Create ( Â Â Â Â Â Â Â Â UINT nSocketPort 0,
        int nSocketType SOCK_STREAM,
        long lEvent FD_READ FD_WRITE
FD_OOB FD_ACCEPT FD_CONNECT FD_CLOSE,
        PCTSTR lpszSocketAddress NULL) - nSocketPort - A port for our socket. If zero (it
is the default) MFC will choose it automatically.
- nSocketType -Â Type of our socket. SOCK_STREAM
for connection oriented sockets and SOCK_DGRAM
for connections message oriented sockets. - lEvent - Events that user wants receive
notifications for them. For example if FD_READ is
included then OnReceive method will be called (of
course when this event will occur). Default value
means that all notifications are included. - lpszSocketAddress - Address of our host to which
we want bind our socket. If it's NULL (it's
default) then one can bind socket with Bind
method. - Returned value is non zero on success and zero
otherwise. Specific error code can be accepted
through GetLastError method.
69Further Info - Useful Sites
- MSDN help files or on the web
- http//msdn.microsoft.com
- http//www2.rad.com/networks/1999/sockets/SockMFC
.htm
70Demo Hw5
- Run (using !) hw5-demo.exe
- Start as server
- Run (using !) hw5-demo.exe
- Start as client //must come after the server
- Draw shapes and see the server and client
communicate - Once the communication is done, each program
should work as before , on its own
71(No Transcript)
72Hints Socket Class for Hw5
- class CClientSocket
-
- SOCKET mySocket
- int Port //port number
- char Server //server's name
- char Buffer //buffer is char array
- int MaxBuffer //maximum buffer
size - ..
- public
- CClientSocket(..) //constructor
- virtual CClientSocket() //destructor
- void Connect()
- int Read()
- void Send(.)
-
- //You will need to fill-in parameters where dots
are.
73Hints Starting as Server or Client
- Start as server or client
- client new CClientSocket("localhost",9999,256,
this) - server new CServerSocket(9999,256,this)
- You may connect to localhost which is a
reserved name for your own computer (where the
program refering to localhost is running) -
- You may also connect to your friends machine as
needed, by specifying the server (through command
line arguments or program settings, as we have
done before)
74Hint Start as Server
- The relationship between the socket and thread
may be as follows (but can be different as well) - void CDrawViewOnStartAsServer()
-
- .
- //create a socket using arbitrary parameters
- server new CServerSocket(9999,1000,this)
- //Listen and accept
- server-gtListen()
- if(connected)
-
- MessageBox("A Client Connected") //inform the
user - myThread new CMyThread(this) //create
thread to read messages - myThread-gtStart() //start thread
-
75Hint thread class
- class CMyThread
-
- public
- CMyThread(CDrawView parent) virtual
CMyThread() - int Start()
- void Run()
- void Close()
- private
- CDrawView Parent //handle to CDrawView
-
- static UINT ThreadFunc (LPVOID pParam)
-
- Note this is just one possibility, you can
construct your thread differently
76Hint thread class
- int CMyThreadStart()
-
- pThreadAfxBeginThread()
-
-
- UINT CMyThreadThreadFunc(LPVOID pParam)
-
- .
-
- You would need to fill these out, if you use this
class given as hint.
77Hints Starting as Server or Client
- void CMyThreadRun()
-
- char buffer
- while (1)
- try
- if (Parent-gtIsServer())
- nRet Parent-gtserver-gtRead(buffer)
- if (nRet -1)
- throw ..
-
- else
- nRet Parent-gtclient-gtRead(buffer)
- if (nRet -1)
- throw ..
-
-
- catch (char str)
-
- Parent-gtMessageBox(str)
78Synchronization
- You dont need synchronization (Mutex objects)
for this homework. - There may be a slight need , like elements being
inserted into the list in the wrong order if both
parties draw at the same time, but this is too
small, unimportant for this homework