LoginSignup
5
6

More than 5 years have passed since last update.

Pythonでサーバークライアント通信を実装してみた【TCP】

Last updated at Posted at 2018-06-11

ソケットプログラミング

サーバークライアント通信方式を採用し、クライアントとサーバー間のチャットを実装しました。
socketというライブラリを活用すると、特に不自由なく動かせました。
1024バイトずつデータを受信します。

self.socket.listen(1)

が無いと、ノンブロッキングのように接続を待たずに、処理を始めてしまうので、今回はエラーを吐くのでご注意。

サーバー側のプログラム

server.py
"""This is a test program"""
import socket

class Server:
    """Server側のクラスを設定"""
    def __init__(self, server_ip, server_port):
        """初期化関数"""
        #ソケットを設定
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        #ブロッキングモードに設定
        self.socket.setblocking(True)

        self.socket.bind((server_ip, server_port))
        self.socket.listen(1)


    def start(self):
        """実行関数"""
        client, addr = self.socket.accept()
        print("connection_by" + str(client))

        while True:
            data = input("server>").encode()
            client.send(data)

            data = client.recv(1024).decode()
            print("crient>", data)

            if not data:
                client.close()
                break

ip = input("ip:")
port = int(input("port:"))
server = Server(ip, port)
server.start()

クライアント側のプログラム

client.py
"""This is client.py"""
import socket

def main():
    """This is a program when it comes to crient"""
    socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    ip = input("ip:")
    port = int(input("port"))
    socket.connect((ip, port))

    while 1:
        data = socket.recv(1024).decode()
        print("server>", data)
        data = input("crient>").encode()
        socket.send(data)

        if not data:
            socket.close()
            break

if __name__ == '__main__':
    main()

おまけ

pylintで文法に関する数々のエラーが出たので

①モジュールや関数に関する説明書きが無い

Missing module docstring
Missing function docstring

②変数が短すぎ

Variable name "s" doesn't conform to snake_case naming style

③whileのあとのカッコの必要なし

Unnecessary parens after 'while' keyword
5
6
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6