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) print(">"+rec.decode('utf-8')) res=input() client.send(res.encode('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: str=input() client.send(str.encode('utf-8')) print("waiting for her response...") response=client.recv(4096) print(">"+response.decode('utf-8'))
実行結果
・サーバ側
> python .\server.py host: 0.0.0.0 port: 50000 from:(クライアント側のIPアドレス) (クライアント側のポート番号) waiting for his response... >hey hi waiting for his response... >what' up eating lunch waiting for his response..
・クライアント側
> python3 .\client.py hey waiting for her response... >hi what' up waiting for her response... >eating lunch
解説
1. サーバ側は接続が完了すると、クライアント側からのデータの送信を待つ。
2. クライアント側がデータを送るとクライアント側はサーバ側からのデータの送信を待つ。
socketライブラリを使ったソケット通信の基礎を学ぶことができた。
(間違い等あればコメントよろしくお願いいたします。)