Windows 8.1 Sockets

27
Consulting/Training Jeremy Likness Principal Consultant [email protected] @JeremyLikness Windows 8.1 Sockets

description

Although Windows Store apps run in a security sandbox, the Windows Runtime provides a rich set of APIs that enable connectivity over sockets. WinRT supports the new HTML5 WebSocket specification but also allows apps to connect via TCP and UDP for real-time streaming connectivity. Join Jeremy Likness as he walks through several examples of apps using socket protocols to establish communications and demonstrates the ease of interfacing with the Windows Runtime sockets APIs.

Transcript of Windows 8.1 Sockets

Page 1: Windows 8.1 Sockets

Consulting/Training

Jeremy Likness

Principal Consultant

[email protected]

@JeremyLikness

Windows 8.1 Sockets

Page 2: Windows 8.1 Sockets

Consulting/Training

consultingWintellect helps you build better software, faster, tackling the tough projects and solving the software and technology questions that help you transform your business. Architecture, Analysis and Design Full lifecycle software development Debugging and Performance tuning Database design and development

trainingWintellect's courses are written and taught by some of the biggest and most respected names in the Microsoft programming industry. Learn from the best. Access the same

training Microsoft’s developers enjoy Real world knowledge and solutions

on both current and cutting edge technologies

Flexibility in training options – onsite, virtual, on demand

Founded by top experts on Microsoft – Jeffrey Richter, Jeff Prosise, and John Robbins – we pull out all the stops to help our customers achieve their goals through advanced software-based consulting and training solutions.

who we are

About Wintellect

Page 3: Windows 8.1 Sockets

Consulting/Training

Sockets, SimplifiedWebSocketsUDP and TCP Sockets Proximity / NFC “Tap to Connect”Bluetooth and Wi-Fi Direct Recap

Agenda

Page 4: Windows 8.1 Sockets

Consulting/Training

Covers full WinRT APIOver 80 example

projectsThis presentation is

based on Chapter 10Full source online at

http://winrtexamples.codeplex.com/

Book available at http://bit.ly/winrtxmpl

WinRT by Example

Page 5: Windows 8.1 Sockets

Consulting/Training

Sockets, Simplified

01011100

Byte

Page 6: Windows 8.1 Sockets

Consulting/Training

Sockets, Simplified

01 02 2A BC 33 FF FA 04

Byte Array

Page 7: Windows 8.1 Sockets

Consulting/Training

Sockets, SimplifiedStream

Length (maybe)

Position

Read

Write

Seek

Page 8: Windows 8.1 Sockets

Consulting/Training

Sockets Are Specialized Streams

Page 9: Windows 8.1 Sockets

Consulting/Training

Berkeley sockets released with Unix in 1983 (owned by AT&T at the time) for “IPC” while I was writing my first Commodore 64 programs in 6502 assembly

Open licensing in 1989 (I had finally moved to IBM PC and MS-DOS)

POSIX API (Portable Operating System Interface) released in 1988

Windows Sockets API (WSA or Winsock) released in 1992 (I graduated high school and discovered the Internet in college) and later implemented for Windows

Another F Ancillary Function Driver (AFD.sys) still exists to this day

Sockets: A Brief History

Page 10: Windows 8.1 Sockets

Consulting/Training

Sockets Are Specialized Streams

Server Responds

“I’d like a stream at 1.2.3.4 on port 80, please”

Client Makes a Call

Page 11: Windows 8.1 Sockets

Consulting/Training

Sockets Are Specialized Streams

1.2.3.4:80

192.168.1.1:3000

192.168.1.1:3001

192.168.1.2:3000

Page 12: Windows 8.1 Sockets

Consulting/Training

A way to communicate between end pointsUsually operate on streams, which are

abstractions over buffers that contain bytesBut can be a datagram that has no connectionA socket connection has two distinct end pointsAn end point is a combination of an address

and a port End points can be hosted on the same

machine, or different machines

Sockets Recap

Page 13: Windows 8.1 Sockets

Consulting/Training

int main(void)

{

struct sockaddr_in stSockAddr;

int Res;

int SocketFD = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);

if (-1 == SocketFD)

{

perror("cannot create socket");

exit(EXIT_FAILURE);

}

memset(&stSockAddr, 0, sizeof(stSockAddr));

stSockAddr.sin_family = AF_INET;

stSockAddr.sin_port = htons(1100);

Res = inet_pton(AF_INET, "192.168.1.1", &stSockAddr.sin_addr);

(void) shutdown(SocketFD, SHUT_RDWR);

close(SocketFD);

return EXIT_SUCCESS;

}

“The Old Days” (still valid 30 yrs. later)

Page 14: Windows 8.1 Sockets

Consulting/Training

Sit on top of TCP (you’ll learn more about TCP later)

Operate over ports 80/443 by default (keeps firewalls happy)

Use HTTP for the initial “handshake” Provide full-duplex communications WinRT implementation allows for

message-based or stream-based

WebSockets

Page 15: Windows 8.1 Sockets

Consulting/Training

GET /info HTTP/1.1

HOST: 1.2.3.4

Upgrade: websocket

Connection: Upgrade

Origin: http://jeremylikness.com/

HTTP/1.1 101 Switching Protocols

Upgrade: websocket

Connection: Upgrade

WebSocket Handshake

Placing my call …

Accepting ….

Now it’s streams from here on out….

Page 16: Windows 8.1 Sockets

Consulting/Training

(a prime example… source code: http://bit.ly/1i5vB9p)

WebSockets

Page 17: Windows 8.1 Sockets

Consulting/Training

Both are communication protocols for delivering octet streams (bytes!)

UDP is fire-and-forget (connectionless)Individual messages sent, i.e. “datagrams” Fast, lots of questions: DNS, DHCP, SNMPTCP is connection-oriented TCP is stream-based Slower, but reliable: HTTP, FTP, SMTP, Telnet

UDP and TCP

Page 18: Windows 8.1 Sockets

Consulting/Training

this.serverSocket = new StreamSocketListener();

this.serverSocket.ConnectionReceived +=

this.ServerSocketConnectionReceived;

await this.serverSocket.BindServiceNameAsync(ServiceName);

// can both read and write messages (full-duplex)

if (serverWriter == null)

{

serverWriter = new DataWriter(args.Socket.OutputStream);

serverReader = new DataReader(args.Socket.InputStream);

}

Server Listens for Connections

Page 19: Windows 8.1 Sockets

Consulting/Training

var hostName = new HostName("localhost");

this.clientSocket = new StreamSocket();

await this.clientSocket.ConnectAsync(hostName, ServiceName);

clientWriter = new DataWriter(this.clientSocket.OutputStream);

clientReader = new DataReader(this.clientSocket.InputStream);

// both client and server require long-running tasks to wait for

// messages and send them as needed

while (true)

{

var data = await GetStringFromReader(clientReader);

// do something with the data

}

Client “Dials In” to Chat

Page 20: Windows 8.1 Sockets

Consulting/Training

(a true adventure… source code: http://bit.ly/1j77rP3)

TCP Sockets

Page 21: Windows 8.1 Sockets

Consulting/Training

Near Field Communications (NFC) is a standard for extremely low powered communications typically very slow and over a very small distance, between devices and/or smart tags

NFC is capable of sending small bursts of information. However, “tap to connect” is a powerful mechanism for establishing a hand-shake to open a stream over other, longer range and faster protocols like Bluetooth and Wi-Fi Direct

Windows Runtime exposes the Proximity APIs that provide a unified way to discover nearby devices and a protocol-agnostic mechanism to connect

Literally you can discover, handshake, etc. and WinRT will “hand-off” a socket that is ready to use (you won’t even know if it is over Wi-Fi Direct or Bluetooth)

Bluetooth = short wavelength wireless technology Wi-Fi Direct = peer to peer over Wi-Fi (wireless cards without requiring a

wireless access point or router)

NFC and Proximity

Page 22: Windows 8.1 Sockets

Consulting/Training

this.proximityDevice = ProximityDevice.GetDefault();

this.proximityDevice.DeviceArrived +=

this.ProximityDeviceDeviceArrived;

this.proximityDevice.DeviceDeparted +=

this.ProximityDeviceDeviceDeparted;

PeerFinder.ConnectionRequested +=

this.PeerFinderConnectionRequested;

PeerFinder.Role = PeerRole.Peer;

PeerFinder.Start();

var peers = await PeerFinder.FindAllPeersAsync();

var socket = await PeerFinder.ConnectAsync(this.SelectedPeer.Information);

Proximity APIs

NFC device and events

Peer Finder (listen and browse)

Browse for peers

Connect to peer

Page 23: Windows 8.1 Sockets

Consulting/Training

1. Try to get Proximity Device (NFC)

2. If exists, register to enter/leave events (NFC)

3. If it supports triggers (i.e. tap) register for connection state change event (NFC)

4. Otherwise browse for peers (Wi-Fi Direct, Bluetooth)

5. When a peer is found, send a connection request

6. Peer must accept the connection request

7. In any scenario, once the connection exists you are passed a stream socket and are free to communicate

Steps for Proximity

Page 24: Windows 8.1 Sockets

Consulting/Training

Source code: http://bit.ly/1jlnGbB

Proximity

Page 25: Windows 8.1 Sockets

Consulting/Training

WebSockets API for simplified WebSocketsSockets API for TCP, UDP, Bluetooth, Wi-Fi

DirectWindows 8.1 is capable of dialing out to any

address and port As a server, most practical example is

listening for Bluetooth connectionsThe security sandbox prevents using

sockets for inter-app communications

Recap

Page 26: Windows 8.1 Sockets

Consulting/Training

Subscribers Enjoy

Expert Instructors

Quality Content

Practical Application

All Devices

Wintellect’s On-DemandVideo Training Solution

Individuals | Businesses | Enterprise Organizations

WintellectNOW.com

Authors Enjoy

Royalty Income

Personal Branding

Free Library Access

Cross-Sell Opportunities

Try It Free! Use Promo Code:

LIKNESS-13

Page 27: Windows 8.1 Sockets

Consulting/Training

Jeremy Likness Source: http://winrtexamples.codeplex.com/

Principal Consultant Book: http://bit.ly/winrtxmpl

[email protected]

@JeremyLikness

Questions?