欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

TCP通信

程序员文章站 2022-03-04 08:48:02
...

服务端

import socket

sk = socket.socket()
ip_port = ("127.0.0.1",8888)
sk.bind(ip_port)
sk.listen(1)

print ("waiting for receiving message!")
conn,address = sk.accept()
msg = "sucessfully connect!"
conn.send(msg.encode())

while True:
    data = conn.recv(1024)
    print ("client:" + data.decode())
    if data == b'exit':
        break
    msg = input("server:")
    conn.send(msg.encode())
    if msg == "exit":
        conn.send(msg.encode())
        break
    
conn.close()

客户端

import socket

client = socket.socket()
ip_port = ("127.0.0.1",8888)
client.connect(ip_port)

data = client.recv(1024)
print (data.decode())

while True:
    msg = input("client:")
    client.send(msg.encode())
    if msg == "exit":  
        break
    data = client.recv(1024)
    print ("server:" + data.decode())
    if data == b'exit':
        break