Add files via upload

This commit is contained in:
Ram Reddy 2021-11-21 17:05:39 -05:00 committed by GitHub
parent 31af44c188
commit aa68141338
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 119 additions and 0 deletions

28
client.py Normal file
View File

@ -0,0 +1,28 @@
import socket
HEADER = 64
PORT = 5050
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = "!DISCONNECT"
SERVER = "10.235.1.101"
ADDR = (SERVER, PORT)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(ADDR)
def send(msg):
message = msg.encode(FORMAT)
msg_length = len(message)
send_length = str(msg_length).encode(FORMAT)
send_length += b' ' * (HEADER - len(send_length))
client.send(send_length)
client.send(message)
print(client.recv(2048).decode(FORMAT))
send("Hello World!")
input()
send("Hello Everyone!")
input()
send("Hello Tim!")
send(DISCONNECT_MESSAGE)

23
client1.py Normal file
View File

@ -0,0 +1,23 @@
import socket
def Main():
host= socket.gethostbyname(socket.gethostname())
port = 4005
server = ('10.235.1.101', 4000)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect((host,port))
message = input("-> ")
while message !='q':
s.sendto(message.encode('utf-8'), server)
data, addr = s.recvfrom(1024)
data = data.decode('utf-8')
print("Received from server: " + data)
message = input("-> ")
s.close()
if __name__=='__main__':
Main()

45
server.py Normal file
View File

@ -0,0 +1,45 @@
import socket
import threading
HEADER = 64
PORT = 5050
SERVER = "10.235.1.101"
# SERVER = socket.gethostbyname(socket.gethostname())
print(SERVER)
ADDR = (SERVER, PORT)
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = "!DISCONNECT"
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
def handle_client(conn, addr):
print(f"[NEW CONNECTION] {addr} connected.")
connected = True
while connected:
msg_length = conn.recv(HEADER).decode(FORMAT)
if msg_length:
msg_length = int(msg_length)
msg = conn.recv(msg_length).decode(FORMAT)
if msg == DISCONNECT_MESSAGE:
connected = False
print(f"[{addr}] {msg}")
conn.send("Msg received".encode(FORMAT))
conn.close()
def start():
server.listen()
print(f"[LISTENING] Server is listening on {SERVER}")
while True:
conn, addr = server.accept()
thread = threading.Thread(target=handle_client, args=(conn, addr))
thread.start()
print(f"[ACTIVE CONNECTIONS] {threading.activeCount() - 1}")
print("[STARTING] server is starting...")
start()

23
server1.py Normal file
View File

@ -0,0 +1,23 @@
import socket
def Main():
host = "10.235.1.101"
port = 4000
print(host)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host, port))
print("Server Started")
while True:
data, addr = s.recvfrom(1024)
data = data.decode('utf-8')
print("Message from: " + str(addr))
print("From connected user: " + data)
data = data.upper()
print("Sending: " + data)
s.sendto(data.encode('utf-8'), addr)
c.close()
if __name__=='__main__':
Main()