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

用Python写一个模拟qq聊天小程序的代码实例

程序员文章站 2022-11-14 08:42:11
python 超简单的聊天程序 客户端: import socket, sys host = '10.248.27.23' # host = raw_inp...

python 超简单的聊天程序

客户端:

import socket, sys
host = '10.248.27.23'
# host = raw_input("plz imput destination ip:")
# data = raw_input("plz imput what you want to submit:")
port = 51423
s = socket.socket(socket.af_inet,socket.sock_stream)
try:
  s.connect((host, port))
except socket.gaierror, e:
  print "address-related error connecting to server: %s" %e
  sys.exit(1)
except socket.error, e:
  print "connection error: %s" %e
  sys.exit(1)
while 1:
  try:
    data = raw_input("i say: ")
    s.send(data)
    buf = s.recv(1024)
    if len(buf):
      print "he say: "+buf
  except:
    print "dialogue over"
    s.close()
    sys.exit(0)

服务器:

import socket, traceback, sys
host = ''
port = 51423
s = socket.socket(socket.af_inet, socket.sock_stream)
s.setsockopt(socket.sol_socket, socket.so_reuseaddr, 1)
s.bind((host, port))
s.listen(1)
clientsock, clientaddr = s.accept()
while 1:
  try:
    buf = clientsock.recv(1024)
    if len(buf):
      print "he say: "+buf
    data = raw_input("i say: ")
    clientsock.sendall(data)
  except:
    print "dialogue over"
    clientsock.close()
    sys.exit(0)

模拟qq聊天,语言环境:python3

示例代码:

# 编写一个程序,模拟qq聊天
# 要求:程序可以同时发消息和收消息,发和收的过程中程序不退出
# 思路:使用socket来完成(socket 是全双工模式,可以实现收和发同时进行),定义俩个线程,一个负责发消息、一个负责收消息
from threading import thread
from socket import *
def rec_data():
  while true:
    rec_info = udpsocket.recvfrom(1024)
    print("\r>>%s:%s" % (rec_info[1], rec_info[0].decode("gb2312")))
    print("<<", end="")
def send_date():
  while true:
    send_mes = input("<<")
    udpsocket.sendto(send_mes.encode("gb2312"), (desip, desport))
udpsocket = none
desip = ""
desport = 0
def main():
  global udpsocket
  global desip
  global desport
  desip = input("对方ip:")
  desport = int(input("对方端口:"))
  udpsocket = socket(af_inet, sock_dgram)
  udpsocket.bind(("", 9001))
  tr = thread(target=rec_data)
  ts = thread(target=send_date)
  tr.start()
  ts.start()
  tr.join()
  ts.join()
if __name__ == '__main__':
  main()

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。如果你想了解更多相关内容请查看下面相关链接