python实现简单的聊天系统

主要还是练习socket包的使用。
server端代码:

import socket
host = socket.gethostname()
port = 12345
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
sock, addr = s.accept()
print('Connection built')
info = sock.recv(1024).decode()
while info != 'exit':
    print('client say: '+ info)
    send_msg = input('server now you say: ')
    sock.send(send_msg.encode())
    if send_msg == 'exit':
        break
    info = sock.recv(1024).decode()
sock.close()
s.close()

client端代码:

import socket

s = socket.socket()
host = socket.gethostname()
port = 12345
s.connect((host, port))
print('connected')
info = ''
while info != 'exit':
    print('server say: '+ info)
    send_msg = input('client now you say: ')
    s.send(send_msg.encode())
    if send_msg == 'exit':
        break
    info = s.recv(1024).decode()
s.close()

用上面的client代码和server代码实现了两个人一问一答的聊天系统:

python实现简单的聊天系统_第1张图片
image.png

参考:
Python实现简单聊天程序

你可能感兴趣的:(python实现简单的聊天系统)