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

python实现简单的聊天

程序员文章站 2022-04-15 22:54:46
# 1.server端 import socket sk=socket.socket() address=('127.0.0.1',8000) sk.bind(address) sk.listen(3) conn,addr = sk.accept() while 1: data=conn.recv( ......
# 1.server端
import socket
sk=socket.socket()
address=('127.0.0.1',8000)
sk.bind(address)
sk.listen(3)
conn,addr = sk.accept()
while 1:
    data=conn.recv(1024)
    print(str(data,'utf8'))
    if not data:
        conn.close()
        conn,addr=sk.accept()
        print(addr)
        continue
    if not data:break
    inp=input('>>>')
    conn.send(bytes(inp,'utf8'))
# 2.client端
import socket
sk=socket.socket()
address=('127.0.0.1',8000)
sk.connect(address)
while true:
    inp=input('>>>')
    if inp=='exit':
        break
    sk.send(bytes(inp,'utf8'))
    data = sk.recv(1024)
    print(str(data, 'utf8'))
sk.close()