Python: File Download & Multi-threaded Chat

File download case
TCP server side:

import socket, os

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

server_socket.bind(('192.168.31.199', 9090))
server_socket. listen(128)

# Receive client requests
client_socket, client_addr = server_socket. accept()
file_name = client_socket.recv(1024).decode('utf8')

# print('Received data from {}address {} port, the content is: {}'.format(client_addr[0], client_addr[1], data))
if os.path.isfile(file_name):
# print('read the file and return to the client')
with open(file_name, 'rb') as file:
content = file. read()
client_socket. send(content)
else:
print('The file does not exist')
TCP client:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.connect(('192.168.31.199', 9090))

# s. send('hello'. encode('utf8'))
file_name = input('Enter the file name you want to download:')
s.send(file_name.encode('utf8'))

with open(file_name, 'wb') as file:
while True:
content = s. recv(1024)
if not content:
break
file. write(content)

s. close()

Multi-threaded chat
Realize chatting on a computer.

import socket, sys
import threading

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(('192.168.31.199', 8080))


def send_msg():
while True:
msg = input('Please enter the content you want to send:')
s.sendto(msg.encode('utf8'), ('192.168.31.199', 9090))
if msg == 'exit':
break


def recv_msg():
while True:
# The data type of data is a tuple
# The 0th element in the tuple is the received data
# The first element in the tuple is the sender's ip address and port number
data, addr = s.recvfrom(1024)
print('Received a message from {}address {} port: {}'.format(addr[0], addr[1], data.decode('utf8')),
file=open('Message record.txt', 'a', encoding='utf8'))


t1 = threading.Thread(target=send_msg)
t2 = threading.Thread(target=recv_msg)

t1. start()
t2. start()

Related Articles

Explore More Special Offers

  1. Short Message Service(SMS) & Mail Service

    50,000 email package starts as low as USD 1.99, 120 short messages start at only USD 1.00

phone Contact Us