Practical Sockets and Threads Derek Weitzel. Windows Threads Concurrent processing Concurrent...

21
Practical Sockets Practical Sockets and Threads and Threads Derek Weitzel Derek Weitzel

Transcript of Practical Sockets and Threads Derek Weitzel. Windows Threads Concurrent processing Concurrent...

Page 1: Practical Sockets and Threads Derek Weitzel. Windows Threads Concurrent processing Concurrent processing Windows Create Thread Windows Create Thread HANDLE.

Practical Sockets and Practical Sockets and ThreadsThreads

Derek WeitzelDerek Weitzel

Page 2: Practical Sockets and Threads Derek Weitzel. Windows Threads Concurrent processing Concurrent processing Windows Create Thread Windows Create Thread HANDLE.

Windows ThreadsWindows Threads

Concurrent processingConcurrent processing Windows Create ThreadWindows Create Thread

• HANDLE WINAPI HANDLE WINAPI CreateThread( LPSECURITY_ATTRIBUTES CreateThread( LPSECURITY_ATTRIBUTES lpThreadAttributeslpThreadAttributes, , SIZE_T SIZE_T dwStackSizedwStackSize, , LPTHREAD_START_ROUTINE LPTHREAD_START_ROUTINE lpStartAddresslpStartAddress, , LPVOID LPVOID lpParameterlpParameter, DWORD , DWORD dwCreationFlagsdwCreationFlags, , LPDWORD LPDWORD lpThreadIdlpThreadId ); );

• Returns HANDLE to new thread, HANDLE is used in other Returns HANDLE to new thread, HANDLE is used in other functions to modify and control the threadfunctions to modify and control the thread

• Usually just pass 0 for lpThreadAttributes, dwStackSize, Usually just pass 0 for lpThreadAttributes, dwStackSize, dwCreationFlags, lpThreadId -> usually used the dwCreationFlags, lpThreadId -> usually used the HANDLEHANDLE

Page 3: Practical Sockets and Threads Derek Weitzel. Windows Threads Concurrent processing Concurrent processing Windows Create Thread Windows Create Thread HANDLE.

Windows ThreadsWindows Threads HANDLE WINAPI CreateThread( HANDLE WINAPI CreateThread(

LPSECURITY_ATTRIBUTES LPSECURITY_ATTRIBUTES lpThreadAttributeslpThreadAttributes, , SIZE_T SIZE_T dwStackSizedwStackSize, , LPTHREAD_START_ROUTINE LPTHREAD_START_ROUTINE lpStartAddresslpStartAddress, , LPVOID LPVOID lpParameterlpParameter, DWORD , DWORD dwCreationFlagsdwCreationFlags, , LPDWORD LPDWORD lpThreadIdlpThreadId ); );

lpStartAddress is a void pointer to a function defined as: lpStartAddress is a void pointer to a function defined as: DWORD WINAPI ThreadProc( LPVOID DWORD WINAPI ThreadProc( LPVOID lpParameterlpParameter ); );

lpParameter is another void pointer to data that you want lpParameter is another void pointer to data that you want passed to the Thread Functionpassed to the Thread Function

Page 4: Practical Sockets and Threads Derek Weitzel. Windows Threads Concurrent processing Concurrent processing Windows Create Thread Windows Create Thread HANDLE.

POSIX Threads (pthreads)POSIX Threads (pthreads)

Same idea as Windows!Same idea as Windows! int pthread_create(pthread_t *thread, int pthread_create(pthread_t *thread,

const pthread_attr_t *attr, const pthread_attr_t *attr, void *(*start_routine)(void*), void *arg);void *(*start_routine)(void*), void *arg);• Must create a pthread_t variable to hold the Must create a pthread_t variable to hold the

thread pointer, used further to control threadthread pointer, used further to control thread• Thread attr can be 0, and I usually use 0Thread attr can be 0, and I usually use 0• Pointer to a function defined as:Pointer to a function defined as:

void* start_routine(void*)void* start_routine(void*)• arg is the void* to the argumentsarg is the void* to the arguments

Page 5: Practical Sockets and Threads Derek Weitzel. Windows Threads Concurrent processing Concurrent processing Windows Create Thread Windows Create Thread HANDLE.

Exiting ThreadsExiting Threads

2 ways:2 ways:• Can exit normally, simply calling exit(int) or Can exit normally, simply calling exit(int) or

reach the end of the Thread Functionreach the end of the Thread Function• Can call special thread functions:Can call special thread functions:

Windows: VOID WINAPI ExitThread( DWORD Windows: VOID WINAPI ExitThread( DWORD dwExitCodedwExitCode ); );Pthreads: void pthread_exit(void *value_ptr);Pthreads: void pthread_exit(void *value_ptr);

Page 6: Practical Sockets and Threads Derek Weitzel. Windows Threads Concurrent processing Concurrent processing Windows Create Thread Windows Create Thread HANDLE.

Force Stop ThreadsForce Stop Threads

Windows:Windows:BOOL WINAPI TerminateThread( HANDLE BOOL WINAPI TerminateThread( HANDLE hThreadhThread, DWORD , DWORD dwExitCodedwExitCode ); ); • Where hThread is the HANDLE returned by the Where hThread is the HANDLE returned by the

CreateThread function.CreateThread function. Pthreads:Pthreads:

• int int pthread_cancel(pthread_cancel(pthread_t threadpthread_t thread););

Page 7: Practical Sockets and Threads Derek Weitzel. Windows Threads Concurrent processing Concurrent processing Windows Create Thread Windows Create Thread HANDLE.

MutexMutex

Used to prevent race conditions with variablesUsed to prevent race conditions with variables Windows:Windows:

• HANDLE HANDLE CreateMutex( LPSECURITY_ATTRIBUTES CreateMutex( LPSECURITY_ATTRIBUTES lpMutexAttributeslpMutexAttributes, BOOL , BOOL bInitialOwnerbInitialOwner, , LPCTSTR LPCTSTR lpNamelpName ); ); where lpMutexAttributes is always 0where lpMutexAttributes is always 0bInitialOwner: TRUE if caller wants ownership, bInitialOwner: TRUE if caller wants ownership, otherwise falseotherwise falselpName: char* to the name of the mutex, used lpName: char* to the name of the mutex, used to distinguish the mutexto distinguish the mutexreturn: HANDLE to the Mutexreturn: HANDLE to the Mutex

Page 8: Practical Sockets and Threads Derek Weitzel. Windows Threads Concurrent processing Concurrent processing Windows Create Thread Windows Create Thread HANDLE.

MutexMutex

Pthread:Pthread:• int pthread_mutex_init( int pthread_mutex_init(

pthread_mutex_t *mutex, const pthread_mutex_t *mutex, const pthread_mutexattr_t *attr);pthread_mutexattr_t *attr);

• Where mutex is the variable to be used for the Where mutex is the variable to be used for the mutexmutex

• Usually use 0 for attrUsually use 0 for attr

Page 9: Practical Sockets and Threads Derek Weitzel. Windows Threads Concurrent processing Concurrent processing Windows Create Thread Windows Create Thread HANDLE.

Locking MutexLocking Mutex

Windows:Windows:• The CreateMutex function automatically locks The CreateMutex function automatically locks

the mutex to the calling thread. The char*the mutex to the calling thread. The char*

Page 10: Practical Sockets and Threads Derek Weitzel. Windows Threads Concurrent processing Concurrent processing Windows Create Thread Windows Create Thread HANDLE.

SocketsSockets

Low-Level Network communicationLow-Level Network communication Most every program that communicates on the Most every program that communicates on the

internet, uses Sockets, though usually abstracted internet, uses Sockets, though usually abstracted through api’sthrough api’s

Page 11: Practical Sockets and Threads Derek Weitzel. Windows Threads Concurrent processing Concurrent processing Windows Create Thread Windows Create Thread HANDLE.

Windows SocketsWindows Sockets

Follows the Berkley Sockets model, with 1 Follows the Berkley Sockets model, with 1 exceptionexception• Must call:Must call:

int WSAStartup( int WSAStartup( WORD WORD wVersionRequestedwVersionRequested, , LPWSADATA LPWSADATA lpWSADatalpWSAData ); );

• These paramaters are difficult to find, so I just These paramaters are difficult to find, so I just use the code:use the code:WSADATA WsaDat;WSADATA WsaDat;

WSAStartup(MAKEWORD(2,2), &WsaDat);WSAStartup(MAKEWORD(2,2), &WsaDat);

Page 12: Practical Sockets and Threads Derek Weitzel. Windows Threads Concurrent processing Concurrent processing Windows Create Thread Windows Create Thread HANDLE.

Berkley SocketsBerkley Sockets

Create the socket:Create the socket:• Int socket(Int socket(

int int socket_familysocket_family, int , int socket_typesocket_type, , int int protocolprotocol););

• Where socket_family is usually PF_INET(linux) Where socket_family is usually PF_INET(linux) or AF_INET(windows) or AF_INET(windows) socket_type can be:socket_type can be:

SOCK_STREAM – TCPSOCK_STREAM – TCP SOCK_DGRAM - UDPSOCK_DGRAM - UDP

• Protocol is usually 0, but can be IPPROTO_TCP Protocol is usually 0, but can be IPPROTO_TCP or IPPROTO_UDP in windowsor IPPROTO_UDP in windows

Page 13: Practical Sockets and Threads Derek Weitzel. Windows Threads Concurrent processing Concurrent processing Windows Create Thread Windows Create Thread HANDLE.

TCP vs DGRAMTCP vs DGRAM TCP:TCP:

• Reliable information transferReliable information transfer• Guaranteed to be in correct order and uncorruptedGuaranteed to be in correct order and uncorrupted• Guaranteed to be received by connected computerGuaranteed to be received by connected computer• Unclear where messages begin and end, stream like Unclear where messages begin and end, stream like

operationoperation UDP:UDP:

• Not guaranteed that the information will reach Not guaranteed that the information will reach connected computerconnected computer

• Not guaranteed to be in order, though guaranteed to be Not guaranteed to be in order, though guaranteed to be un-corruptedun-corrupted

• Clear beginning and endClear beginning and end

Page 14: Practical Sockets and Threads Derek Weitzel. Windows Threads Concurrent processing Concurrent processing Windows Create Thread Windows Create Thread HANDLE.

Socket FunctionsSocket Functions

Bind:Bind:• int bind( SOCKET int bind( SOCKET ss, const struct sockaddr* , const struct sockaddr* namename, int , int namelennamelen ); );

Binds to the specified ip (usually your own) Binds to the specified ip (usually your own) and portand port

Usually used for server side, to Listen for Usually used for server side, to Listen for connectionsconnections

Page 15: Practical Sockets and Threads Derek Weitzel. Windows Threads Concurrent processing Concurrent processing Windows Create Thread Windows Create Thread HANDLE.

Socket FunctionsSocket Functions

ListenListen• int listen( SOCKET int listen( SOCKET ss, int , int backlogbacklog ); ); • Socket s specifies socket created by socket Socket s specifies socket created by socket

functionfunction• Backlog is max length of queue of incoming Backlog is max length of queue of incoming

connectionsconnections• Used to listen for incoming connections, accept Used to listen for incoming connections, accept

connections with accept functionconnections with accept function

Page 16: Practical Sockets and Threads Derek Weitzel. Windows Threads Concurrent processing Concurrent processing Windows Create Thread Windows Create Thread HANDLE.

Socket FunctionsSocket Functions

AcceptAccept• Used mostly on server side communicationUsed mostly on server side communication• SOCKET accept( SOCKET SOCKET accept( SOCKET ss, ,

struct sockaddr* struct sockaddr* addraddr, int* , int* addrlenaddrlen ); );• Returns the connected socketReturns the connected socket• SOCKET s is the listening socketSOCKET s is the listening socket• Addr is the structure to hold the address Addr is the structure to hold the address

information of the socketinformation of the socket• Addrlen is the sizeof addrAddrlen is the sizeof addr

Page 17: Practical Sockets and Threads Derek Weitzel. Windows Threads Concurrent processing Concurrent processing Windows Create Thread Windows Create Thread HANDLE.

Socket FunctionsSocket Functions SendSend

• Used to send informationUsed to send information• Send for TCP:Send for TCP:

int send( SOCKET int send( SOCKET ss, const char* , const char* bufbuf,,int int lenlen, int , int flagsflags ); );

Buf is character array of length lenBuf is character array of length len• Send for UDP:Send for UDP:

int sendto( SOCKET int sendto( SOCKET ss, const char* , const char* bufbuf, int , int lenlen, int , int flagsflags, const struct sockaddr* , const struct sockaddr* toto, int , int tolentolen ); );

to is structure specifing the receiver of the packetto is structure specifing the receiver of the packet

Page 18: Practical Sockets and Threads Derek Weitzel. Windows Threads Concurrent processing Concurrent processing Windows Create Thread Windows Create Thread HANDLE.

Socket FunctionsSocket Functions

Receive for TCPReceive for TCP• int recv( SOCKET int recv( SOCKET ss, char* , char* bufbuf,,

int int lenlen, int , int flagsflags ); );• Returns amount of bytes read in (a char is a Returns amount of bytes read in (a char is a

byte in length, normally)byte in length, normally)• buf is a character array previously made of buf is a character array previously made of

length lenlength len• Flags can be left as 0Flags can be left as 0

Page 19: Practical Sockets and Threads Derek Weitzel. Windows Threads Concurrent processing Concurrent processing Windows Create Thread Windows Create Thread HANDLE.

Socket FunctionsSocket Functions

Receive for UDPReceive for UDP• int recvfrom( SOCKET int recvfrom( SOCKET ss, char* , char* bufbuf, int , int lenlen, ,

int int flagsflags, struct sockaddr* , struct sockaddr* fromfrom, , int* int* fromlenfromlen ); );

• From is structure to hold the sender’s From is structure to hold the sender’s information of length fromleninformation of length fromlen

Page 20: Practical Sockets and Threads Derek Weitzel. Windows Threads Concurrent processing Concurrent processing Windows Create Thread Windows Create Thread HANDLE.

Socket FunctionsSocket Functions

SelectSelect• Used to poll the condition of sockets, useful to Used to poll the condition of sockets, useful to

see status of multiple of socketsee status of multiple of socket• int select( int int select( int nfdsnfds, fd_set* , fd_set* readfdsreadfds, ,

fd_set* fd_set* writefdswritefds, fd_set* , fd_set* exceptfdsexceptfds, , const struct timeval* const struct timeval* timeouttimeout ); );

• Nfds is largest value of the sockets (they’re Nfds is largest value of the sockets (they’re ints)ints)

• Fd_set provides macros, shown in examplesFd_set provides macros, shown in examples

Page 21: Practical Sockets and Threads Derek Weitzel. Windows Threads Concurrent processing Concurrent processing Windows Create Thread Windows Create Thread HANDLE.

ResourcesResources

www.msdn.comwww.msdn.com – Microsoft – Microsoft Developer NetworkDeveloper Network

http://www.yolinux.com/TUTORIALS/Lhttp://www.yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.htmlinuxTutorialPosixThreads.html - pthread tutorial - pthread tutorial