CS138-lecture-20210304

Socket programming #

image_2021-03-04-09-04-45 image_2021-03-04-09-07-11 image_2021-03-04-09-10-57 image_2021-03-04-09-12-58 image_2021-03-04-09-16-42

UDP Client in Python #

SOCK_DGRAM means it will use UDP. The server’s socket is always open.

UDPClient.py:

from socket import *
serverName = 'hostname'
serverPort = 12000
clientSocket = socket(AF_NET, SOCK_DGRAM)
message = raw_input('Input lowercase sentence:')
clientSocket.sendto(message, (serverName, serverPort))
modifiedMessage, serverAddress = clientSocket.recvfrom(2048)
print modifiedMessage
clientSocket.close()

UDPServer.py

from socket import *
serverPort = 12000
serverSocket = socket(AF_INET, SOCK_DGRAM)
serverSocket.bind(('', serverPort))
print 'The server is ready to receieve'
while 1:
    message, clientAddress = serverSocket.recvfrom(2048)
    modifiedMessage = message.upper()
    serverSocket.sendto(modifiedMessage, clientAddress)

Port numbers should be between 1024-65536.

TCP Client in Python #

image_2021-03-04-09-39-38 image_2021-03-04-09-44-46 image_2021-03-04-09-45-25 image_2021-03-04-09-49-56

SOCK_STREAM means it will use TCP.

TCPClient.py

from socket import *
serverName = 'servername'
serverPort = 12000
clientSocket = socket(AF_NET, SOCK_STREAM)
clientSocket.connect((serverName, serverPort))
sentence = raw_input('Input a lowercase sentence:')
clientSocket.send(sentence)
modifiedSentence = clientSocket.recv(1024)
print 'From server:', modifiedSentence
clientSocket.close()

TCPServer.py

from socket import *
serverPort = 12000
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(('', serverPort))
serverSocket.listen(1)
print 'The server is ready'
while 1:
    connectionSocket, addr = serverSocket.accept()
    sentence = connectionSocket.recv(1024)
    capitalizedSentence = sentence.upper()
    connectionSocket.send(capitalizedSentence)
    connectionSocket.close()

image_2021-03-04-10-05-35