Skip to content
This repository has been archived by the owner on Sep 9, 2021. It is now read-only.

Liubchenkova Anna 203 lab1a #15

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions lab1a/client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import socket
import time
import datetime
import threading

#converts from Greenwich time to local time
def local_time(time_of_message):
timezone = -time.timezone / 3600
time_of_message_format = datetime.datetime.strptime(time_of_message, "%H:%M")
local_time_of_message = time_of_message_format + datetime.timedelta(hours=timezone)
time_format = datetime.datetime.strftime(local_time_of_message, "%H:%M")
return time_format

#recieve message from clients and print it
class ReceivingThread(threading.Thread):
def __init__(self, server_socket):
threading.Thread.__init__(self)
self.ssocket = server_socket

def run(self):
while True:
length_of_message = int(self.ssocket.recv(8).decode('UTF-8'))
time_of_message = self.ssocket.recv(5).decode('UTF-8')
length_name = int(self.ssocket.recv(8).decode('UTF-8'))
name = self.ssocket.recv(length_name).decode('UTF-8')
chunks = []
bytes_record = 0
while bytes_record < length_of_message:
chunk = self.ssocket.recv(length_of_message)
if chunk == b'':
raise RuntimeError("The socket connection is broken")
chunks.append(chunk)
bytes_record = bytes_record + len(chunk)
data = b''.join(chunks)
time_of_message = local_time(time_of_message)
print("<" +time_of_message + "> "+ "[" + name + "] " + data.decode("UTF-8"))

#make the connection
SERVER = "127.0.0.1"
PORT = 7000
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((SERVER, PORT))
login = input("Please, write your username: ")
client.send(bytes(login, 'UTF-8'))
print("Now you can start a conversation!")
thread_receive = ReceivingThread(client)
thread_receive.start()
while True:
out_data = input()
length = '{:08d}'.format(len(out_data))
client.send(bytes(str(length), 'UTF-8'))
client.send(bytes(datetime.datetime.utcnow().strftime("%H:%M"), 'UTF-8'))
client.send(bytes(out_data, 'UTF-8'))
if out_data == 'exit()':
break
client.shutdown(socket.SHUT_WR)
client.close()
110 changes: 110 additions & 0 deletions lab1a/server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import socket
import threading

all_sockets = {}
data = ""
socket_from = socket
names = {}
length = 0
time = 0

#convert string to bytes
def to_bytes(text):
text_to_bytes = bytes(text, 'UTF-8')
return text_to_bytes

#send message to all clients exsept who send the message
def send_to_all(msg, sock):
global all_sockets
global names
global socket_from
global time
for a in all_sockets.keys():
if all_sockets[a] != sock:
all_sockets[a].send(msg)
return len(msg)

#receiving messages from clients
class ReceivingThread(threading.Thread):
def __init__(self, client_address, client_socket):
threading.Thread.__init__(self)
self.csocket = client_socket
self.cadrress = client_address

def run(self):
global all_sockets
all_sockets[self.cadrress] = self.csocket
global time
global data
global names
global length
global socket_from
client_login = self.csocket.recv(2048).decode('UTF-8')
names[self.csocket] = client_login
while True:
length = int(self.csocket.recv(8).decode('UTF-8'))
time = self.csocket.recv(5).decode('UTF-8')
print(time)
socket_from = self.csocket
chunks = []
bytes_record = 0
#check whole message or not
while bytes_record < length:
chunk = self.csocket.recv(length)
if chunk == b'':
raise RuntimeError("The socket connection is broken")
if chunk == "exit()":
break
chunks.append(chunk)
bytes_record = bytes_record + len(chunk)
data = b''.join(chunks)
print("Client:", data)

#send messages to another clients
class SendingThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)

def run(self):
global length
while True:
total_sent = 0
global data
global names
global socket_from
global time
while total_sent < int(length):
if data != '':
name_length = '{:08d}'.format(len(names[socket_from]))
length_name_message = '{:08d}'.format((int(length)))
send_to_all(to_bytes(length_name_message), socket_from)
send_to_all(to_bytes(time), socket_from)
send_to_all(to_bytes(name_length), socket_from)
send_to_all(to_bytes(names[socket_from]), socket_from)
sent = send_to_all(data[total_sent:], socket_from)
data = ""
if sent == 0:
raise RuntimeError("socket connection broken")
total_sent = total_sent + sent
print("send length"+length_name_message)


def main():
#make the connection
localhost = "127.0.0.1"
port = 7000
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((localhost, port))
print("Server is running")
#connect no more than 5 clients
server.listen(5)
sending_thread = SendingThread()
sending_thread.start()
while True:
client_sock, client_address = server.accept()
thread_receive = ReceivingThread(client_address, client_sock)
thread_receive.start()


if __name__ == '__main__':
main()