Winsock Programming Blocking and Asynchronous Sockets for Windows.

Slides:



Advertisements
Similar presentations
Computer Net Lab/Praktikum Datenverarbeitung 2 1 Overview Sockets Sockets in C Sockets in Delphi.
Advertisements

Socket Programming Application Programming Interface.
Windows Sockets Purpose Windows Sockets 2 (Winsock) enables programmers to create advanced internet, intranet, and other network-capable applications to.
Tutorial 8 Socket Programming
CS 311 – Lecture 18 Outline IPC via Sockets – Server side socket() bind() accept() listen() – Client side connect() Lecture 181CS Operating Systems.
Client Server Model The client machine (or the client process) makes the request for some resource or service, and the server machine (the server process)
ISP – 9 th Recitation Socket programming – Client side.
1 Socket Programming A crash-course in network programming…
CS 360 – Spring 2007 Pacific University TCP section 6.5 (Read this section!) 27 Feb 2007.
Network Programming Sockets and Winsock. Please Be Responsible We all know that the Internet is full of security holes –most of them do not require any.
Socket Programming References: redKlyde ’ s tutorial set Winsock2 for games (gamedev.net)
CS1652 September 13th, 2012 The slides are adapted from the publisher’s material All material copyright J.F Kurose and K.W. Ross, All Rights.
ECE 4110 – Internetwork Programming Client-Server Model.
Sockets and intro to IO multiplexing. Goals We are going to study sockets programming as means to introduce IO multiplexing problem. We will revisit socket.
Fall 2000Datacom 11 Socket Programming Review Examples: Client and Server-Diagnostics UDP versus TCP Echo.
TCP/IP Protocol Stack IP Device Drivers TCPUDP Application Sockets (Gate to network) TCP: –Establish connection –Maintain connection during the communication.
Network Programming Tutorial #9 CPSC 261. A socket is one end of a virtual communication channel Provides network connectivity to any other socket anywhere.
2: Application Layer 1 Chapter 2: Application layer r 2.1 Principles of network applications r 2.2 Web and HTTP r Internet gaming r 2.3 FTP r 2.4 Electronic.
Sirak Kaewjamnong Computer Network Systems
Server Sockets: A server socket listens on a given port Many different clients may be connecting to that port Ideally, you would like a separate file descriptor.
CS162B: IPv4 Socketing Jacob T. Chan. Socketing in the Real World  Most computer games are multiplayer in nature or have multiplayer components  DotA,
The Socket Interface Chapter 21. Application Program Interface (API) Interface used between application programs and TCP/IP protocols Interface used between.
Socket Programming Lec 2 Rishi Kant. Review of Socket programming Decide which type of socket – stream or datagram. Based on type create socket using.
1 COMP445 Fall 2006 Lab assignment 1. 2 STEP1: Get the name of the second party STEP2: Get phone number from white pages CALLERRECEIVER STEP1: Plug the.
Networking Tutorial Special Interest Group for Software Engineering Luke Rajlich.
CS 158A1 1.4 Implementing Network Software Phenomenal success of the Internet: – Computer # connected doubled every year since 1981, now approaching 200.
1 Computer Networks An Introduction to Computer Networks University of Tehran Dept. of EE and Computer Engineering By: Dr. Nasser Yazdani Lecture 3: Sockets.
Introduction to Socket
Chapter 27 Socket API Interface The interface between an application program and the communication protocols in an operating system is known as the Application.
Socket Programming Tutorial Department of Computer Science Southern Illinois University Edwardsville Fall, 2015 Dr. Hiroshi Fujinoki
Socket Programming Lab 1 1CS Computer Networks.
Sockets Socket = abstraction of the port concept: –Application programs request that the operating system create a socket when one is needed –O.S. returns.
GUI-Based Programming ECE 417/617: Elements of Software Engineering Stan Birchfield Clemson University.
2: Application Layer1 Chapter 2: Application layer r 2.1 Principles of network applications r 2.2 Web and HTTP r 2.3 FTP r 2.4 Electronic Mail  SMTP,
Programming with UDP – II Covered Subjects: Creating UDP sockets Client Server Sending data Receiving data Connected mode.
S OCKET P ROGRAMMING IN C Professor: Dr. Shu-Ching Chen TA: HsinYu Ha.
Intro to Socket Programming CS 360. Page 2 CS 360, WSU Vancouver Two views: Server vs. Client Servers LISTEN for a connection and respond when one is.
S OCKET P ROGRAMMING IN C Professor: Dr. Shu-Ching Chen TA: Hsin-Yu Ha.
Read() recv() connection establishment Server (connection-oriented protocol) blocks until connection from client Client socket() bind() listen() accept()
2: Application Layer 1 Socket Programming UNIX Network Programming, Socket Programming Tutorial:
Socket Programming. Computer Science, FSU2 Interprocess Communication Within a single system – Pipes, FIFOs – Message Queues – Semaphores, Shared Memory.
1 Spring Semester 2008, Dept. of Computer Science, Technion Internet Networking recitation #7 Socket Programming.
Lecture 3 TCP and UDP Sockets CPE 401 / 601 Computer Network Systems slides are modified from Dave Hollinger.
Socket Programming in C CS587x Lecture 3 Department of Computer Science Iowa State University.
Socket Programming Jignesh Patel Palanivel Rathinam connecting processes.
1 Socket Interface. 2 Client-Server Architecture The client is the one who speaks first Typical client-server situations  Client and server on the same.
Socket Programming(1/2). Outline  1. Introduction to Network Programming  2. Network Architecture – Client/Server Model  3. TCP Socket Programming.
1 Socket Interface. 2 Basic Sockets API Review Socket Library TCPUDP IP EthernetPPP ARP DHCP, Mail, WWW, TELNET, FTP... Network cardCom Layer 4 / Transport.
Sockets and Beginning Network Programming
Sockets and Beginning Network Programming
Jim Fawcett CSE 681 – Software Modeling & Analysis Fall 2002
CS 1652 Jack Lange University of Pittsburgh
Socket Programming in C
Socket Interface 1 Introduction 11 Socket address formats 2 API 12 13
Transport layer API: Socket Programming
TCP Sockets Programming
28.
Socket Programming.
Chapter 2: Application layer
TCP/IP Socket Programming in C
Chapter 3 Socket API © Bobby Hoggard, Department of Computer Science, East Carolina University These slides may not be used or duplicated without permission.
Socket Programming(1/2)
Sockets Programming Socket to me!.
Sockets Programming Socket to me!.
Socket Programming Neil Tang 09/08/2008
Internet Networking recitation #8
Sockets.
Jim Fawcett CSE 681 – Software Modeling & Analysis Summer 2003
Chapter 2: Application layer
Presentation transcript:

Winsock Programming Blocking and Asynchronous Sockets for Windows

History MS-DOS/Windows not designed for networking Early Microsoft operating systems ignored the TCP/IP stack “Visionary” Bill Gates supports NETBIOS over TCP/IP Several packages offered by 3 rd parties “Trumpet Winsock” None work particularly well

What is Winsock? API, SPI and ABI –API for application developers –SPI for network software vendors –ABI to ensure consistent interoperability between applications and various implementations of Winsock Less important now that Microsoft has released a quality Winsock –No significant alternatives

The API Based on BSD sockets API –First of many Microsoft “hacks” Complications due to differences between Unix and Windows –errno (Unix) vs. WSAGetLastError() –BSD sockets based on C and Unix fork() File descriptors

Example: The Unix Way while (1) { newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen); if (newsockfd < 0) error("ERROR on accept"); pid = fork(); if (pid < 0) error("ERROR on fork"); if (pid == 0) { close(sockfd); dostuff(newsockfd); exit(0); } else close(newsockfd); }

Steps to a Listen Socket Initialize Winsock Fill out SOCKADDR_IN (define the socket) Create the socket bind() the socket Make the socket listen() Wait on accept() Handle clients via socket returned by accept()

Example: Listening (simplified) // INITIALIZE sockVersion = MAKEWORD(1, 1); // Winsock version 1.1 WSAStartup(sockVersion, &wsaData); // CREATE SOCKET SOCKET listeningSocket; listeningSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); // DEFINE SOCKET SOCKADDR_IN serverInfo; serverInfo.sin_family = AF_INET; serverInfo.sin_addr.s_addr = INADDR_ANY; serverInfo.sin_port = htons(8888); // BIND bind(listeningSocket, (LPSOCKADDR)&serverInfo, sizeof(struct sockaddr)); // LISTEN listen(listeningSocket, 10); // ACCEPT SOCKET theClient; theClient = accept(listeningSocket, NULL, NULL);

Steps to Connecting Initialize Winsock Fill out HOSTENT Create socket Fill out SOCKADDR_IN Connect Send/recv

Example: Connecting (simplified) // INITIALIZE sockVersion = MAKEWORD(1, 1); WSAStartup(sockVersion, &wsaData); // FILL OUT HOSTENT LPHOSTENT hostEntry = gethostbyname(" // CREATE SOCKET SOCKET theSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); // FILL OUT SOCKADDR_IN SOCKADDR_IN serverInfo; serverInfo.sin_family = AF_INET; serverInfo.sin_addr = *((LPIN_ADDR)*hostEntry->h_addr_list); serverInfo.sin_port = htons(80); // CONNECT connect(theSocket, (LPSOCKADDR)&serverInfo, sizeof(struct sockaddr));

Sending and Receiving int send(SOCKET s, char * buf, int len, int flags); –Returns number of bytes sent or SOCKET_ERROR int recv(SOCKET s, char * buf, int len, int flags); –Returns number of bytes received or SOCKET_ERROR Send and recv must be done in loops to ensure all data is sent/received

Problem: blocking Many of these functions “block” –accept() –connect() –send() –recv() One solution: poll sockets using select() Another solution: threads Coolest solution: asynchronous sockets

Why Asynchronous? Windows handles polling for you Familiar Windows message paradigm Easy to read code

Why NOT Asynchronous? Non-portable Microsoft is evil Use them anyways, they are cool

Windows Messages Message queue Message pump –“first chance” message handling Message Handler –Callback function

Sample Message Pump HRESULT hRet; UINT Msg; while( (hRet = GetMessage( &Msg, NULL, 0, 0 )) != 0) { if (hRet == -1) { PostQuitMessage(1); } else { TranslateMessage(&Msg); DispatchMessage(&Msg); } }

Sample Message Handler LRESULT CALLBACK WinProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch(uMsg) { case WM_DESTROY: PostQuitMessage(WM_QUIT); break; default: return FALSE; } return TRUE; }

How Does This Apply? Windows sends messages when sockets are waiting –No need to poll –No need for many threads –Create sockets and go about other tasks –Handle sockets just like any other Windows control

Making a socket asynchronous int PASCAL WSAAsyncSelect(SOCKET s, HWND hwnd, unsigned int Msg, long event ); Simple call to WSAAsyncSelect:

Message and Events Five events: –FD_READ –FD_WRITE –FD_CONNECT –FD_ACCEPT –FD_CLOSE –OR these together to tell Windows what notifications you need User defined messages –WM_USER + n

Handling the message wParam: –socket instance lParam: –HIWORD: 0 (success) Error code –LOWORD: FD_READ, FD_WRITE, etc.

Example: Handling FD_ACCEPT SOCKET s; switch (msg) { case WM_USER + 5: switch(WSAGETSELECTEVENT(lParam) { case FD_ACCEPT: s = accept(wParam, NULL, NULL); break; } break; }

Summary Why this is important: –Current Winsock responsible for increase in quantity and popularity of Internet applications –Almost all applications use the Internet somehow, or could be improved by using the Internet

Example: Version Checking DWORD WINAPI CGlowdotChatServer::DoVersionCheckThreadProc(LPVOID pvoid) { struct sockaddr_in sa; struct hostent *hp; hp = gethostbyname(“ memset(&sa,0,sizeof(sa)); // set address and port memcpy((char *)&sa.sin_addr, hp->h_addr, hp->h_length); sa.sin_family = hp->h_addrtype; sa.sin_port = htons((u_short)VERSION_CHECK_PORT); // create socket SOCKET s = socket(hp->h_addrtype, SOCK_STREAM, 0); std::string request ("GET /glowdotchat/server/checkversion.php?getcurrentversion=yes HTTP/1.1\nUser- Agent:Mozilla\nHost: send(s, request.c_str(), request.length(),0); char buf[1000]; std::string response(""); recv(s, buf, 1000, 0); response += std::string(buf); std::string::size_type pos1 = response.find(std::string(" ")); std::string::size_type pos2 = response.find(std::string(" ")); response = response.substr(pos1 + 17, pos2 - pos1 - 17); if (response == std::string(VERSION)) { // server up to date } else { // new version available } return 0; }