lessons period 2
This commit is contained in:
31
period_2/01-sockets/803/client.py
Normal file
31
period_2/01-sockets/803/client.py
Normal file
@@ -0,0 +1,31 @@
|
||||
import socket
|
||||
|
||||
HOST = socket.gethostbyname("localhost")
|
||||
PORT = 5052
|
||||
|
||||
def send(msg):
|
||||
|
||||
|
||||
# create a message input
|
||||
message = msg.encode("utf-8")
|
||||
|
||||
# create and bind socket
|
||||
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
socket.connect((HOST, PORT))
|
||||
|
||||
# send message
|
||||
socket.send(b'-' * (64 - len(str(len(message)).encode("utf-8"))))
|
||||
socket.send(message)
|
||||
|
||||
socket.recv(1024)
|
||||
|
||||
print("Message sent")
|
||||
socket.close()
|
||||
|
||||
message = input("Please enter a message: ")
|
||||
|
||||
if message == "":
|
||||
send("!DISCONNECT")
|
||||
|
||||
else:
|
||||
send(message)
|
34
period_2/01-sockets/803/server.py
Normal file
34
period_2/01-sockets/803/server.py
Normal file
@@ -0,0 +1,34 @@
|
||||
import socket
|
||||
# Get local machine name
|
||||
HOST = socket.gethostname("localhost")
|
||||
PORT = 5050
|
||||
|
||||
def handleClient(clientsocket):
|
||||
while True:
|
||||
# Receive no more than 1024 bytes
|
||||
msg = clientsocket.recv(1024)
|
||||
if not msg:
|
||||
break
|
||||
clientsocket.send(msg)
|
||||
clientsocket.close()
|
||||
|
||||
def start():
|
||||
# Create a socket object
|
||||
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
|
||||
|
||||
# Bind to the port
|
||||
serversocket.bind((HOST, PORT))
|
||||
|
||||
# Queue up to 5 requests
|
||||
serversocket.listen(5)
|
||||
|
||||
while True:
|
||||
# Establish a connection
|
||||
clientsocket, addr = serversocket.accept()
|
||||
|
||||
print("Got a connection from %s" % str(addr))
|
||||
|
||||
msg = 'Thank you for connecting' + "\r\n"
|
||||
clientsocket.send(msg.encode('ascii'))
|
||||
clientsocket.close()
|
Reference in New Issue
Block a user