【问题标题】:Python: Print data while waiting for inputPython:在等待输入时打印数据
【发布时间】:2015-03-30 04:00:08
【问题描述】:

正在编写一个聊天程序,并希望它能够在收到消息时打印正在接收的消息,同时用户可以向其他人输入消息。目前程序向其他计算机发送消息,然后接收其他计算机的消息,然后重复。

import sys
import socket as so
import platform
from socket import *
import string
import base64
import os
import random

dmi = 0
lmi = 0 
host = ""
checkcode = ''.join(random.choice('0123456789QWERTYUIOPLKJHGFDSAZXCVBNMasdfgjhklpoiuytrewqmnzbxvc') for i in range(16))
BLOCK_SIZE = 32
hostl = raw_input("> Input IP of computer message will be sent to: ")
port = 13000
buf = 1024
addr = (host, port)
addrl = (hostl, port)
UDPSock = socket(AF_INET, SOCK_DGRAM)
UDPSock.bind(addr)
addr = (host, port)
addrl = (hostl, port)
while dmi == 0:
    datal = raw_input("Enter message to send or type 'exit': ")
    UDPSock.sendto(datal, addrl)
    if datal == "exit":
        UDPSock.close()
        dmi +=1
    (data, addr) = UDPSock.recvfrom(buf)
    print "Received message: "+ data
print "Done!"

不要问我导入的不需要的库,这是一个测试脚本。

【问题讨论】:

    标签: python sockets loops


    【解决方案1】:

    您需要学习如何使用多线程 (http://www.tutorialspoint.com/python/python_multithreading.htm)。一个线程等待用户输入,而另一个线程接收消息并打印出来。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-27
      • 1970-01-01
      • 1970-01-01
      • 2019-11-27
      • 1970-01-01
      • 2021-12-07
      • 1970-01-01
      相关资源
      最近更新 更多