Win 32 Sockets
Win 32 Sockets
Jim Fawcett
CSE 687 – Object Oriented Design
Spring 2015
References
Socket
recv buffer bytes
recv buffer
Socket addresses
struct SOCKADDR_IN {
sin_family // AF_INET
sin_address.s_addr // inet_addr(“127.0.0.1”);
sin_port // htons(8000);
} addr;
socket() socket()
bind()
listen()
accept() connect()
recv() send()
send() recv()
close() close()
Accessing Sockets Library
#include <winsock2.h>
To build a server for multiple clients you will need to use threads,
e.g.:
#include <process.h>
terminate thread
shutdown
closesocket (on listener socket)
WSACleanup
WSAStartup
wVersionRequested = MAKEWORD(1,1);
WSAData wData;
lpWSAData = &wData
int WSAStartup(
WORD wVersionRequested,
LPWSADATA lpWSAData
)
Loads WS2_32.dll
TCP/IP socket
af = AF_INET
type = SOCK_STREAM
protocol = IPPROTO_IP
int bind(
SOCKET s,
const struct sockaddr *name,
int namelen
)
SOCKET accept(
SOCKET s,
struct sockaddr *addr,
int *addrLen
)
Client
Client
Socket Server Main Thread
data Server
port Socket
use socket
data
Thread
Create
listener listener
port socket
recv
int recv(
SOCKET s,
char *buff,
int len,
int flags
)
struct sockaddr_in{
short sin_family;
unsigned short sin_port;
struct in_addr sin_addr;
char sin_zero[8];
} SOCKADDR_IN;
TCP/IP Address fields
sin_family AF_INET
sin_port at or above 1024
sin_addr inet_addr(“127.0.0.1”);
sin_zero padding
int connect(
SOCKET s,
const struct sockaddr *name,
int namelen
)
Process #1 Process #2
function receiving
data from
Process #1
Store and Forward Architecture
Process #1 - Main Thread Process #2 - Main Thread
Interprocess
socket socket
Communication
SendQ RecvQ
MessageMgr
Model
thread-safe asynchronous messages thread-safe
MessageMgr MessageMgr
queues and data transfers queues
sockets model
bidirectional - server listens, spawns a
sockets byte stream
sockets thread for each client
Talk Protocol
The hardest part of a client/server socket
communication design is to control the active
participant
receiving sending
/send token
/extract message /send message
/send token
/send token
sending receiving
/send done
/extract token
/send message /extract message
Each connection channel
contains one “sending” token. Client
Message Length
Another vexing issue is that the receiver may not
know how long a sent message is.
Browser/server
ftp
SOAP
Network applications
What we didn’t talk about
udp protocol
socket select(…) function
non-blocking sockets
Sockets
The End