Network Programming: Socket Programming PDF

Document Details

Ameera

Uploaded by Ameera

University of Sharjah

Dr. Ala Altaweel

Tags

socket programming networking computer science python

Summary

This document details network programming, specifically socket programming, using UDP and TCP. It includes example application implementations in Python.

Full Transcript

Network Programming: Socket Programming Dr. Ala Altaweel University of Sharjah Department of Computer Engineering [email protected] 1 Application Layer: Overview  Principles of network applicat...

Network Programming: Socket Programming Dr. Ala Altaweel University of Sharjah Department of Computer Engineering [email protected] 1 Application Layer: Overview  Principles of network applications  Socket programming with UDP and TCP  Single‐Threaded v.s. Muti‐ Threaded  Web and HTTP  The Domain Name System DNS Socket Programming: 2‐2 Socket programming goal: learn how to build client/server applications that communicate using sockets socket: door between application process and end‐end‐transport protocol application application socket controlled by process process app developer transport transport network network controlled link by OS link Internet physical physical Socket Programming: 2‐3 Socket programming Two socket types for two transport services:  UDP: unreliable datagram  TCP: reliable, byte stream‐oriented Application Example: 1. client reads a line of characters (data) from its keyboard and sends data to server 2. server receives the data and converts characters to uppercase 3. server sends modified data to client 4. client receives modified data and displays line on its screen Socket Programming: 2‐4 Socket programming with UDP UDP: no “connection” between client and server: no handshaking before sending data sender explicitly attaches IP destination address and port # to each packet receiver extracts sender IP address and port# from received packet UDP: transmitted data may be lost or received out‐of‐order Application viewpoint:  UDP provides unreliable transfer of groups of bytes (“datagrams”) between client and server processes Socket Programming: 2‐5 Client/server socket interaction: UDP server (running on serverIP) client create socket: create socket, port= x: clientSocket = serverSocket = socket(AF_INET,SOCK_DGRAM) socket(AF_INET,SOCK_DGRAM) Create datagram with serverIP address And port=x; send datagram via read datagram from clientSocket serverSocket write reply to serverSocket read datagram from specifying clientSocket client address, port number close clientSocket Socket Programming: 2‐6 Example app: UDP client Python UDPClient include Python’s socket library from socket import * serverName = 'localhost' serverPort = 12000 create UDP socket for server clientSocket = socket(AF_INET, SOCK_DGRAM) get user keyboard input message = raw_input('input lowercase sentence:') attach server name, port to message; send into socket clientSocket.sendto(message.encode(), (serverName, serverPort)) read reply characters from socket into string modifiedMessage, serverAddress = clientSocket.recvfrom(2048) print out received string print ('The server replied with: ' + modifiedMessage.decode()) print the server address print(serverAddress) Socket Programming: 2‐7 close the socket clientSocket.close() Example app: UDP server Python UDPServer from socket import * serverPort = 12000 create UDP socket serverSocket = socket(AF_INET, SOCK_DGRAM) bind socket to local port number 12000 serverSocket.bind(('', serverPort)) print ('The server is ready to receive') loop forever while True: Read from UDP socket into message, getting message, clientAddress = serverSocket.recvfrom(2048) client’s address (client IP and port) receivedMessage = message.decode() print received message from client print('The server received: ' + str(receivedMessage)) modifiedMessage = receivedMessage.upper() print modified message to be sent to client print('The server to send: ' + str(modifiedMessage)) print(clientAddress) send modified message to client serverSocket.sendto(modifiedMessage.encode(), clientAddress)Socket Programming: 2‐8 Socket programming with TCP Client must contact server  when contacted by client, server server process must first be TCP creates new socket for server running process to communicate with that server must have created socket particular client (door) that welcomes client’s allows server to talk with multiple contact clients Client contacts server by: source port numbers used to distinguish clients (as we presented Creating TCP socket, specifying IP before) address, port number of server process Application viewpoint when client creates socket: client TCP provides reliable, in‐order TCP establishes connection to byte‐stream transfer (“pipe”) server TCP between client and server processes Socket Programming: 2‐9 Client/server socket interaction: TCP server (running on hostIP) client create socket, port=x, for incoming request: serverSocket = socket() wait for incoming create socket, connection request TCP connect to hostIP, port=x connectionSocket = connection setup clientSocket = socket() serverSocket.accept() send request using read request from clientSocket connectionSocket write reply to connectionSocket read reply from clientSocket close connectionSocket close clientSocket Socket Programming: 2‐10 Example app: TCP client Python TCPClient from socket import * serverName = '127.0.0.1' serverPort = 12000 create TCP socket for server, remote port clientSocket = socket(AF_INET, SOCK_STREAM) 12000 establish the connection with server clientSocket.connect((serverName,serverPort)) sentence = raw_input('Input lowercase sentence:') clientSocket.send(sentence.encode()) No need to attach server name, port modifiedSentence = clientSocket.recv(1024) print ('From server: ' + str(modifiedSentence.decode())) clientSocket.close() Socket Programming: 2‐11 Example app: TCP server Python TCPServer from socket import * serverPort = 12000 create TCP welcoming socket serverSocket = socket(AF_INET,SOCK_STREAM) serverSocket.bind(('',serverPort)) server begins listening for incoming TCP requests. 3 connections kept waiting if server is busy (the 4th will serverSocket.listen(3) be rejected) print('The server is ready to receive') loop forever while True: server waits on accept() for incoming connectionSocket, addr = serverSocket.accept() requests, new socket created on return read bytes from socket (but sentence = connectionSocket.recv(1024).decode() not address as in UDP) print('The server received: ' + str(sentence)) capitalizedSentence = sentence.upper() print('The server to send: ' + str(capitalizedSentence)) close connection to this client (but not connectionSocket.send(capitalizedSentence.encode()) welcoming socket) connectionSocket.close() Socket Programming: 2‐12 TCP Client‐Server to Send and Receive Files Let’s develop a new protocol to send and receive files using TCP Client‐Server model Server is running and listening to clients' requests Client issues GET command to receive a named file from server’s working directory Client issues SEND command to send a file to the server from client’s working directory This represents the similar steps towards designing all application protocols like HTTP, FTP, Chat, etc Socket Programming: 2‐13 TCP Client‐Server to Send and Receive Files Python TCPServer import the required libraries import socket import sys import os.path import operator server port number serverPort = 7005 #create socket object for server serverSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) #socket is bound to localhost and port 7005 serverSocket.bind(('',serverPort)) socket bind to local IP address and server port #accept up to 2 incoming waiting connections serverSocket.listen(2) server is listening to clients’ connections #server start to listen on localhost and port print ('Server listening...') Socket Programming: 2‐14 TCP Client‐Server to Send and Receive Files Python TCPServer get server name #get the host name of the server print ("Server machine name:", socket.gethostname()) #get the ip address of the host name print ("Server IP address: ", socket.gethostbyname(socket.gethostname())) print ("Server Port #: ", serverPort) keep accepting client’s requests while True: get server IP address by name #accept() returns a socket object from client with addr address socket and address of connected client connectionSocket, addr = serverSocket.accept() #connection established with client print ('Got connection from client: ', addr) #waiting for GET or SEND command from client print ('Waiting for a command from client...') read issued command client_request = connectionSocket.recv(1024) from client Socket Programming: 2‐15 TCP Client‐Server to Send and Receive Files Python TCPServer #convert from byte object so we can read as string request_str = client_request.decode("utf-8") #server receives GET command from client #server should read the file to be sent back to client handle GET command if request_str == 'GET': print('Server received GET command from client. Waiting for filename...') #server reads the file name read and decode file’s client_request = connectionSocket.recv(1024) name file_name = client_request.decode("utf-8") #open, reads, and send the file to client f = open(file_name, "rb") print('Sending file...') Socket Programming: 2‐16 TCP Client‐Server to Send and Receive Files Python TCPServer send 1 K byte each l = f.read(1024) time keep sending while(l): until done connectionSocket.send(l) l = f.read(1024) f.close() print('Done with sending file: ', str(file_name)) #server receives SEND command from client #server should create a file to be received by the client handle SEND elif request_str == 'SEND': command print('Server received SEND command from client.') #open, receive, and write file from client #file will be named from_client f = open("from_client", "wb") print('Receiving file..') receive 1 K byte each l = connectionSocket.recv(1024) time Socket Programming: 2‐17 TCP Client‐Server to Send and Receive Files Python TCPServer keep receiving all bytes while(l): f.write(l) l = connectionSocket.recv(1024) f.close() print('Done with receiving file from client') close client’s socket connectionSocket.close() Socket Programming: 2‐18 TCP Client‐Server to Send and Receive Files Python TCPClient import the required libraries import socket import sys #hardcoded before moving on to user input ignore this In case the user does not want to enter the server IP #serverName = 'localhost' address and port number #serverPort = 7005 In case the user wants to enter the server IP address and serverName = raw_input('Enter server IP: ') port number print(serverName) serverPort = int(raw_input('Enter port number: ')) Socket Programming: 2‐19 TCP Client‐Server to Send and Receive Files Python TCPClient #in this loop, sockets open and close for each request the client makes keep reading client’s requests while True: #create socket object for client clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) clientSocket.connect((serverName,serverPort)) print('Connected to server.') read user command and send it to server sentence = raw_input('Enter a GET or SEND command:') print(sentence) clientSocket.send(sentence.encode('utf-8')) read file name and send it to server fileName = raw_input('\nEnter name of file: ') Socket Programming: 2‐20 clientSocket.send(fileName.encode('utf-8'))

Use Quizgecko on...
Browser
Browser