Python Socket聊天程序 Python使用Socket实现简单聊天程序

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Python Socket聊天程序 Python使用Socket实现简单聊天程序

Tynam.Yang   2021-04-21 我要评论

b2b模式的聊天工具

服务端:

# 链接
while True:
 print('等待连接...')
 sock,adr = server_socket.accept()
 while True:
  try:
   # 接受数据
   data = sock.recv(1024)
   print(adr[0] + '发来消息:', data.decode())
   # 发送数据
   send_msg = input("请输入发送内容>>").strip()
   sock.send(send_msg.encode('utf-8'))
  except ConnectionResetError as e:
   print('%s断开连接!' %adr[0])
   break
 # 关闭本次连接
 sock.close()
# 关闭socket
server_socket.close()

客户端:

import socket

# 设置服务器ip和端口号
host_ip = '192.168.31.207'
port = 8896
client_socket = socket.socket()
client_socket.connect((host_ip,port))

while True:
 send_msg = input('请输入内容>>').strip()
 if send_msg == '':
  continue
 client_socket.send(send_msg.encode())
 recv_data = client_socket.recv(1024)
 print(host_ip+"回复:"+recv_data.decode())

client_socket.close()

目前只支持客户端发一句,服务端发一句这种模式。

超过一句内容后,发出去的内容对方接收不到

结果:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们