230 likes | 464 Views
Socket Programming. With TCP and UDP. Christoffer Brodd-Reijer Zaruhi Aslanyan. Socket. High level connection between two hosts Identified by port+IP Transport layer (UDP, TCP, etc) or raw IP. Socket. Similar to operating on a file: open read/write close. Socket.
E N D
Socket Programming With TCP and UDP • ChristofferBrodd-Reijer • ZaruhiAslanyan
Socket • High level connection between two hosts • Identified by port+IP • Transport layer (UDP, TCP, etc) or raw IP
Socket Similar to operating on a file: • open • read/write • close
Socket Systematic overview:
TCP • Transmission Control Protocol • Created in 1974 • Operates on of a stream of octets (bytes)
TCP Proc • Connection orientated • Reliable • Ordered Cons • Slow • Complex Good for • World Wide Web • Remote administration • File transfer (FTP) • Electronic mail (SMTP)
TCP Using TCP sockets in C on UNIX: // create socket s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP) // receive data recvfrom(s, buf, len, flags, &scr_addr, &addrlen) // send data sendto(s, buf, len, flags, &dect_addr, addrlen)
TCP Using TCP sockets in Java: // create socket Socket s = new Socket(address, port); // receive data InputStream in = s.getInputStream(); // send data OutputStream out = s.getOutputStream();
TCP Using TCP sockets in Ruby: // create socket s = TCPSocket.new(host, port) // receive data str = s.recv(len[, flags]) // send data s.send(mesg, flags[, to])
TCP Using TCP sockets in Python: // create socket s = socket.socket([socket.AF_INET[,socket.SOCK_STREAM]]) // receive data socket.recv(bufsize[, flags]) // send data socket.sendall(string[, flags])
UDP • User Datagram Protocol • Created in 1980 • Operates on whole datagrams (messages); not bytes
UDP Cons: • Unreliable delivery • Unreliable order • Possible duplication Pros: • Simple • Fast Good for: • Streaming • Gaming • Name lookup (DNS) • Time lookup (NTP)
UDP Using UDP sockets in C on UNIX: // create socket s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP) // receive data recvfrom(s, buf, LEN, 0, &opt, &optlen) // send data sendto(s, buf, LEN, 0, &opt, optlen)
UDP Using UDP sockets in Java: // create socket s = new DatagramSocket(PORT); // receive data p = new DatagramPacket(buf, buf.length); s.receive(p); // send data p = new DatagramPacket(buf, buf.length, IP, PORT) s.send(p);
UDP Using UDP sockets in Ruby: // create socket s = UDPSocket.new // receive data msg, sender = s.recv_from MAXLEN // send data s.send msg, OPTIONS
UDP Using UDP sockets in Python: // create socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) // receive data msg = s.recv(MAXLEN) // send data s.sendall(msg)
Summary • Socket: End-to-End handler • TCP: connection, bytes, reliable • UDP: datagrams, fast, simple • Code is similar between languages (same principles applies)