TCP单线程连接

服务端代码

from socket import *

server_addr = ("0.0.0.0", 8080)
sock = socket()
sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
sock.bind(server_addr)
sock.listen(5)

while True:
    print("waiting for connecting....")
    try:
        connf, addr = sock.accept()
        print("Connect from:", addr)
    except KeyboardInterrupt:
        print("server exit")
        break
    except Exception as e:
        print(e)
        continue

    while True:
        try:
            data = connf.recv(1024)
        except Exception as e:
            print(e)
            break
        if not data:
            break
        print(data.decode())
        n = connf.send(b"OK")
        print("send %d byte" % n)
    connf.close()
sock.close()

客户端

from socket import *

server_addr = ("192.168.27.189", 8080)
sock = socket()
print("waiting for connecting....")
try:
    sock.connect(server_addr)
except Exception as e:
    print(e)
    sys.exit(0)
print("connected...")
while True:
    msg = input("Msg>>")
    if not msg:
        break
    sock.send(msg.encode())
    data = sock.recv(1024)
    if not data:
        break
    print(data)
sock.close()

你可能感兴趣的:(tcp/ip,网络,服务器)