Python: File Download & Multi-threaded Chat

ファイルダウンロードのケース
TCP サーバー側:

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)

# クライアントリクエストを受信
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 クライアント:

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()

マルチスレッドチャット
コンピュータでチャットを実現します。

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:
# data のデータ型はタプル
# タプルの 0 番目の要素は受信データ
# タプルの 1 番目の要素は送信者の IP アドレスとポート番号
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 お問い合わせ
Hi, I'm Alibaba Cloud AI Assistant!
I can help with questions and solutions.