Socket Programming
Two types of packets
- UDP: unreliable datagram
- TCP: reliable byte stream
Actually it takes the same amount of time to send UDP packet and TCP packet!!
Even streaming services uses TCP these days.
UDP
- no handshaking before sending data (no connection!)
- sender explictly attaches IP destination address and port number to each packet
- receiver extracts sender IP address and port number from received packet
Programming UDP
1 | int socket(PF_INET, SOCK_DGRM, IPPROTO_UDP); |
For historical reasons, intel uses little endian, and internet uses big endian... You need to tkae care endianness!1
2
3
4int port;
struct sockaddr_in saddr;
saddr.sin_port = htons(port);
Programming TCP
UDP just sends sockets.
TCP must make connection before sending sockets!
Usually server opens well-known port. (e.g. HTTP: 80)
- Client contact server
- Server creates new socket dedicated for that client
- Client and server sends messages
1 | int connect(int socket, struct sockaddr *address,int addr_len); |
listen's arguments accepts queue size!
Probably your server need 1024 queue size, if you're not accepting fast enough.
Unfortunately, listen use signle queue, and it's not designed with a multi-core environment in mind.