编写聊天程序,并且正在寻找能够在用户可以向其他人输入消息时打印正在接收的消息的能力。目前程序将消息发送到其他计算机,然后接收另一台计算机的消息,然后重复。
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!"
不要询问我导入的不需要的库,这是一个测试脚本。
答案 0 :(得分:0)
您需要学习如何使用多个线程(http://www.tutorialspoint.com/python/python_multithreading.htm)。一个线程等待用户输入,而另一个线程接收消息并打印它们。