socket programming with php
TRANSCRIPT
Socket Programming with PHPBack to the Basics
In the beginning There was a process
and the process ran well
but it needed to talk to another process
“Use IPC and all shall be clear”
IPC Inter Process Communication
File
Signal
Socket
Pipe
Named Pipe
Semaphore
…
But which do I need?
Are the processes on the same computer?
Does it need to support multiple OS types?
Communication needs to be one way or two way?
Network SocketsAll things internet
Layers of Fun IP – forwards packets of data based on a
destination address
TCP – verifies the correct delivery of data from client to server with error and lost data correction
Network Sockets – subroutines that provide TCP/IP (and UDP and some other support) on most systems
Acronym Madness The DOD section DARPA built ARPANET
which ran on TCP/IP and the protocols are maintained by IETF
TCP - Transmission Control Protocol
IP – Internet Protocol
UDP - User Datagram Protocol
Packet of Data
What are Sockets?Programming 101
Wormholes! Sockets are just like "worm holes" in
science fiction. When things go into one end, they (should) come out of the other.
Types Connection-Oriented
“Ack?”
“Syn-Ack”
“Syn!”
Connectionless
0x49424d434f52504f524154494f3e32303036
Data Flow Simplex – one way street
Half-Duplex – can send up and down, BUT only one at a time
Full-Duplex – can send up and down at the SAME time
BSD SocketsBerkley / Posix and everything in between
BSD -> Posix Everybody used BSD
“Hey, it might be smart to standardize this”
“Excellent, let’s just use BSD basically”
Posix sockets == BSD sockets with very minor alterations
Network Socket Types
Stream
Connection oriented (tcp)
Datagram
Connectionless (udp)
Raw
Low level protocols
Where are we going?
Addresses
Ports
Doing it with PHP“Oh yeah, I guess PHP does have all those apis…”
StreamsMaking things dead easy
What is a Stream? Access input and output generically
Can write and read linearly
May or may not be seekable
Comes in chunks of data
How PHP Streams Work
Stream Contexts
Stream Wrapper
Stream FilterALL IO
Definitions Socket
Bidirectional network stream that speaks a protocol
Transport
Tells a network stream how to communicate
Wrapper
Tells a stream how to handle specific protocols and encodings
Built in Socket Transports
tcp
udp
unix
udg
SSL extension
ssl
sslv2
sslv3
tls
Things to watch for! Sockets block
stream_set_blocking
stream_set_timeout
stream_select
feof means “connection_closed”?
huge reads or writes (think 8K)
stream_get_meta_data is READ ONLY
Using Sockets
stream_socket_client
stream_socket_server
Sockets ExtensionAll the power of C apis, all the pain of C apis
Almost C, but not quite
Wrapper around BSD sockets api
Some of the declarations are different
You really need to know how sockets work
Like writing in C without the hassles
A core extension but NOT a default extension
Possibly noisy, use an error handler
Keep your man handy
PHP
socket_create
socket_listen
socket_bind
socket_read
C man page
socket
listen
bind
read
Create First socket_create
domain (IPv4, IPv6, unix)
type – stream for tcp and dgram for udp is the usual
protocol – hint, you can pass 0 to get the “default” protocol for the type
Listen socket_bind
$socket
address
port
socket_listen
$socket
backlog
socket_create_listen
port
backlog
create
bind
listen
and Accept socket_accept
$socket
gives you a NEW socket resource to read off of, but you can’t accept off the newly created socket resource it returns
Or Connect socket_connect
$socket
address (ipv4 or 6 depending on what you set)
port
Read and Write socket_write
$socket
data
len (will truncate to this!)
socket_read
$socket
length
type (stop on newlines or grab as binary)
Grab Data socket_recv - usually connected socket
socket_recvfrom - from a specific address and port
socket_recvmsg – grabs a whole message (datagram’s friend)
Send Data socket_send
socket_sendmsg
socket_sendto
All done! socket_shutdown – stop reading and writing
socket_close – all done, close it down
Blocking, Selecting socket_select
socket_set_block
socket_set_unblock
what – no poll?
Poll vs. Select select - has existed for a great while and
exists almost everywhere.
poll - Not existing on older unixes nor in Windows before Vista. Broken implementation in Mac OS X at least up to 10.4
Interoperability
<?php
$stream = stream_socket_server("udp://0.0.0.0:58380”,$errno, $errstr, STREAM_SERVER_BIND);
$sock = socket_import_stream($stream);
?>
socket_import_stream
There’s a lot more! setting options
errors
READ THE C MAN PAGES!
WebsocketsTCP on bidirectional full-duplex acid
RFC 6455 HTML5 protocol
New and shiny
Take the place of ajax, polling, and other hackery
Allow cross origin communications
Websockets are… based on TCP
look like an “upgrade” request to HTTP clients/servers
reduce latency and overhead
full-duplex on a single socket
usable with proxies
bi-directional
allow polling and streaming without pain
persistent…. wait - persistent?
Hmmm - persistent Websockets are persistent connections
Your $server_of_choice may not like this
newer nginx is smart about proxying them
apache has some websockets modules
IIS8 and higher has support as well
use a standalone php server
If using fastcgi/php-fpm, you’re going to eat processes
How DO they DO it?
NIH will kill you Rachet - http://socketo.me
Wrench - https://github.com/varspool/Wrench
PHPWS - https://github.com/Devristo/phpws
Wamp Websocket Application Messaging Protocol
“OMG THEY STOLE OUR ACRONYM!”
Async RPC
Async sub/pub
Implementation https://github.com/cballou/php-websockets-
demos
https://developer.mozilla.org/en-US/docs/WebSockets/Writing_WebSocket_client_applications
http://www.binarytides.com/websockets-php-tutorial/
http://srchea.com/blog/2011/12/build-a-real-time-application-using-html5-websockets/
Websockets Resources
http://www.websocket.org
http://wamp.ws
http://tools.ietf.org/html/rfc6455
http://socket.io (use to make client sides less stupid)
http://www.w3.org/TR/websockets/
My Little Project
Pick a good C websockets library
libwebsockets - http://libwebsockets.org
Wrap it up for PHP
Profit???
Contact [email protected]
@auroraeosrose
http://emsmith.net
http://github.com/auroraeosrose
Freenode
#phpwomen
#phpmentoring
#php-gtk