Socket - Python

server.py

import socket
import time

ENCODING = "UTF-8"
CMD_SEND = "pwd2"
CMD_RECV = "pwd"
HOST = "192.168.0.110"
PORT = 666


def server_start(host, port):
    """
    Virtual machine as server, host="192.168.118.128"
    Laptop as client, host="192.168.118.128"
    """

    mode = "recv"

    server = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
    server.bind((host, port))
    server.listen(1)
    print(f"\033[0;31m[服务端 {time.strftime('%H:%M:%S', time.localtime(time.time()))}] "
          f"Waiting for connection ..."
          f"\033[0m")

    while True:
        conn, address = server.accept()
        while True:
            if mode == "recv":
                # Receive
                data_recv = conn.recv(1024)
                if len(data_recv) > 0:
                    print(f"\033[0;31m[服务端 {time.strftime('%H:%M:%S', time.localtime(time.time()))}] "
                          f"{data_recv.decode(encoding=ENCODING)}"
                          f"\033[0m")
                    # Send
                    conn.send(bytes("Ok", encoding=ENCODING))
                else:
                    break

                if data_recv.decode(encoding=ENCODING) == CMD_RECV:
                    mode = "send"
            elif mode == "send":
                data = input(f"\033[0;32m[服务端 {time.strftime('%H:%M:%S', time.localtime(time.time()))}] \033[0m")
                if len(data) == 0 or data in ["exit", "quit", "q"]:
                    break
                conn.send(bytes(data, encoding=ENCODING))
                data_recv = conn.recv(1024)
                if len(data_recv) > 0:
                    print(f"\033[0;32m[客户端 {time.strftime('%H:%M:%S', time.localtime(time.time()))}] "
                          f"{data_recv.decode(encoding=ENCODING)}"
                          f"\033[0m")
                if data == CMD_SEND:
                    mode = "recv"

        conn.close()
        break
    server.close()


if __name__ == "__main__":
    server_start(host=HOST, port=PORT)

client.py

import socket
import time

ENCODING = "UTF-8"
CMD_SEND = "pwd2"       # The client converts to the sender when a command is entered on the server end.
CMD_RECV = "pwd"        # The client converts to the receiver when a command is entered on the client end.
HOST = "192.168.0.110"
PORT = 666


def client_start(host, port):
    mode = "send"

    client = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
    client.connect((host, port))
    try:
        while True:
            if mode == "send":
                data = input(f"\033[0;32m[客户端 {time.strftime('%H:%M:%S', time.localtime(time.time()))}] \033[0m")
                if len(data) == 0 or data in ["exit", "quit", "q"]:
                    break
                # Send
                client.send(bytes(data, encoding=ENCODING))
                # Receive
                data_recv = client.recv(1024)
                if len(data_recv) > 0:
                    print(f"\033[0;32m[客户端 {time.strftime('%H:%M:%S', time.localtime(time.time()))}] "
                          f"{data_recv.decode(encoding=ENCODING)}"
                          f"\033[0m")

                if data == CMD_RECV:
                    mode = "recv"
            elif mode == "recv":
                data_recv = client.recv(1024)
                if len(data_recv) > 0:
                    print(f"\033[0;31m[客户端 {time.strftime('%H:%M:%S', time.localtime(time.time()))}] "
                          f"{data_recv.decode(encoding=ENCODING)}"
                          f"\033[0m")
                    client.send(bytes("Ok", encoding=ENCODING))
                else:
                    break
                if data_recv.decode(encoding=ENCODING) == CMD_SEND:
                    mode = "send"

    except Exception as e:
        print(e)
    client.close()


if __name__ == "__main__":
    client_start(host=HOST, port=PORT)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值