1. 程式人生 > >python3網路程式設計實戰

python3網路程式設計實戰

客戶端程式:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Version: python 3.6.3
# Tools: Pycharm 2017.3.3

__date__ = '2018/7/24 11:06'
__author__ = 'cdl'

import socket
import time

class ChatClient:
    def __init__(self, username, port):
        self.username = username
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.connect(("127.0.0.1", port))

    def send_msg(self, msg):
        self.socket.send("{username}::{msg}".format(username=self.username,msg=msg).encode("utf-8"))

    def recv_msg(self):
        data=self.socket.recv(1024)
        if data:
            print("\n【機器人小圖】"+" "+time.strftime('%Y-%m-%d:%H:%M:%S',time.localtime(time.time())))
            print(data.decode("utf-8"))
            return True
        return False

    def main(self):
        data = self.socket.recv(1024)
        print(data.decode("utf-8"))
        msg = input("請輸入訊息:")
        self.send_msg(msg)
        while True:
            if self.recv_msg():
                msg=input("\n我:")
                self.send_msg(msg)
                if msg == "exit":
                    print("聊天室已關閉")
                    break

if __name__ == '__main__':
    cc = ChatClient(username="Curry", port=9999)
    cc.main()


服務端程式:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Version: python 3.6.3
# Tools: Pycharm 2017.3.3

__date__ = '2018/7/24 11:22'
__author__ = 'cdl'
import socket
import time
import threading
import requests
import json


class ChatServer:
    def __init__(self, port):
        # 繫結伺服器的ip和埠,注意以tuple的形式
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.bind(("0.0.0.0", port))
        self.socket.listen(5)
        # 圖靈機器人,授權碼
        self.key = "XXXXXXXXXXXX(自己申請一個圖靈機器人的key)"
        print("正在監聽 127.0.0.1 :{}...".format(port))

    def tcplink(self, sock, addr):
        # 每次連線,開始聊天前,先歡迎下。
        sock.send("你好,歡迎來到機器人聊天器!".encode("utf-8"))
        while True:
            data = sock.recv(1024).decode("utf-8")
            print(sock.getpeername())
            print(sock.getsockname())
            print(sock.fileno())
            username = data.split("::")[0]
            msg = data.split("::")[1]
            if msg == "exit":
                break
            if msg:
                print("【"+username+"】 "+time.strftime('%Y-%m-%d:%H:%M:%S',time.localtime(time.time())))
                print(msg)
                response = self.get_response(msg)
                sock.send(response.encode("utf-8"))
        sock.close()
        print("與 {} 結束聊天!".format(username))

    def get_response(self, info):
        # 呼叫圖靈機器人API
        url = 'http://www.tuling123.com/openapi/api?key=' + self.key + '&info=' + info
        res = requests.get(url)
        res.encoding = 'utf-8'
        jd = json.loads(res.text)
        return jd['text']

    def main(self):
        while True:
            sock, addr = self.socket.accept()
            t=threading.Thread(target=self.tcplink, args=(sock, addr))
            t.start()

if __name__ == '__main__':
    cs = ChatServer(port=9999)
    cs.main()

執行:

# 將服務端程式跑起來,然後執行客戶端