chinda_fall_desu’s diary

竹内豊の日記

ヒューマンコンピューターインターフェースをもっと知りたいなー

pythonでsocketを使って通信を行う② (ファイルの送受信)

今回は前回作ったコードを改良して、テキストファイルを送信できるようにする。

ソースコード
・サーバ側

import socket

bind_host="0.0.0.0"
bind_port=50000

server=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((bind_host, bind_port))
server.listen(5)
print("host: "+bind_host)
print("port: "+str(bind_port))

while True:
    client, addr=server.accept()
    print("from:"+ addr[0]+" "+str(addr[1]))
    while True:
        print("waiting for his response...")
        rec=client.recv(1024)
        fd=open("get.txt", "wb")
        fd.write(rec)
        fd.close()
        print(rec.decode('utf-8'))
        if len(rec)==0:
            client.close()
            break

・クライアント側

import socket
target_host="(サーバ側のIPアドレス)"
target_port=50000
client=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((target_host, target_port))
while True:
    while True:
        file=input("textfile: ")
        try:
            fd=open(file, "rb")
        except FileNotFoundError:
            print("can't open this file")
            print("please try it again")
            print("")
        else:
            text=fd.read()
            fd.close()
            break
    client.send(text)
    print("succeed")
    print("")

・送るテキストファイル (send.txt)

hello!
my name is Alex


実行結果
・サーバ側

> python .\server.py
host: 0.0.0.0
port: 50000
from:(クライアント側のIPアドレス)(クライアント側のポート番号)
waiting for his response...
hello!
my name is Alex

waiting for his response...

・クライアント側

> python .\client.py
textfile: fdsa
can't open this file
please try it again

textfile: send.txt
succeed

textfile:

・得られたファイル (get.txt)

hello!
my name is Alex


解説
1.サーバ側はクライアント側からの接続を待ち、接続後はデータの送信を待つ。
2. クライアント側はテキストファイル名を入力する。


ファイアウォールの設定等が原因で送れないことがあるので注意。


(間違い等あればコメントよろしくお願いいたします。)