Socket

image.png

UDP: connectionless

image.png

interaction

image.png

UDP socket

import socket

# format: socket(family, type)
# AF_INET: the address family for IPv4
# AF_INET6: IPv6
# SOCK_STREAM: TCP socket
# SOCK_DGRAM: UDP socket
# AF_UNIX: communication between processes on the same machine
socket(AF_INET, SOCK_DGRAM)

socket.bind(socket_address)  # socket_address: ip+port

bytes_sent = socket.sendto(bytes, peer_socket_addr)

recv_bytes, sender_peer_addr = socket.recvfrom(bufsize)  # bufsize: the maximum number of bytes to receive from the socket

socket.close()
# UDP client
serverName = ‘hostname’
serverPort = 12000
clientSocket = socket(AF_INET, SOCK_DGRAM)

message = raw_input(’Input lowercase sentence:’)
clientSocket.sendto(message.encode(), (serverName, serverPort))

modifiedMessage, serverAddress = clientSocket.recvfrom(2048)
print(modifiedMessage.decode())
clientSocket.close()

### UDP server
serverPort = 12000
serverSocket = socket(AF_INET, SOCK_DGRAM)
serverSocket.bind(('', serverPort))
print ("The server is ready to receive")

while True:
		message, clientAddress = serverSocket.recvfrom(2048)
		modifiedMessage = message.decode().upper()
		serverSocket.sendto(modifiedMessage.encode(), clientAddress)

TCP: connection-oriented

image.png

interaction

image.png

TCP socket

import socket

# server
server_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(server_address)

# backlog: how many connections can be waiting to be processed
server_socket.listen([backlog])  # listening on the well-known port
while True:
	connection, sender_id = server_socket.accept() # returns connection socket
	connection.recv(bufsize)
	connection.send(bytes)
	connection.close()

# client
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(socket_addr) 
client_socket.send(bytes) # no need to specify the addr since there is a connection socket
client_socket.recv(bufsize)
client_socket.close()

TCP services