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

2020-09-23 0 690

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()

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

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

结果:

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自学编程网。

遇见资源网 Python Python使用Socket实现简单聊天程序 http://www.ox520.com/24599.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务