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

简单的socket例子

程序员文章站 2022-04-09 13:11:51
...

客户端代码(client.py)


import socket

client = socket.socket()
client.connect(('localhost',8080))

while True:
    data = input('>>>')
    client.send(data.encode('utf-8'))#data必须为字节序列

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

client.close()

服务端代码(server.py)

import socket

server = socket.socket()
server.bind(('localhost',8080))
server.listen()

while True:
    conn,addr = server.accept()

    while True:
        data = conn.recv(1024)
        if not data:
            print('the client is lost!!!')
            break
        print('>>>',data.decode())
        data = input('>>>').encode('utf-8')
        conn.send(data.encode('utf-8'))

server.close()

转载于:https://www.jianshu.com/p/b70fd9ab34ae