因此,我开始使用UDP编写客户端-服务器程序,它可以很好地接收消息,但是采用这种方式,它将在收到并打印出一条消息后关闭服务器应用程序。因此,我决定添加一个while循环,但是问题是,除非我在其顶部有一个print语句,而且我不知道为什么,否则该循环将不会执行。这是到目前为止我双方的代码。
客户:
import socket
# Define address and port
UDP_IP_ADDRESS = "127.0.0.1"
UDP_PORT_NO = 31000
Message = [None] * 200 #Max message of 200 bytes
res = []
clientSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Make sure the user's credentials match possibilities inside userpass.txt
# userpass.txt format: username:password
def checkCreds(usernameInput, passwordInput):
with open('userpass.txt') as f:
credentials = [x.strip().split(':', 1) for x in f]
for username, password in credentials:
if username == usernameInput and password == passwordInput:
print "Your credentials match!"
return True
# Handle a login to send a message
# Main input should be send into main
# Handled in the form of username&password
def login(credentials):
userPass = credentials.split("&")
if (checkCreds(userPass[0], userPass[1])):
Message[0] = "c"
Message[1] = "b"
Message[2] = '\x04'
Message[3] = raw_input("Message to send: ")
for val in Message:
if val != None :
res.append(val)
sendMsg = ''.join(map(str, res))
clientSock.sendto(sendMsg, (UDP_IP_ADDRESS, UDP_PORT_NO))
del res[:]
# Allows user input to login with specific username and password
# Format: login#username&password
def main():
while True:
userInput = raw_input()
function = userInput.split("#")
if function[0] == "login":
login(function[1])
main()
服务器:
import socket, sys
from itertools import islice
# Define address and port
UDP_IP_ADDRESS = "127.0.0.1"
UDP_PORT_NO = 31000
# Set up socket
serverSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Bind the socket
serverSock.bind((UDP_IP_ADDRESS, UDP_PORT_NO))
def main():
while True:
#Receive a message and print it out
data, addr = serverSock.recvfrom(1024)
print "Message: ",
for c in islice(data, 3, len(data)):
sys.stdout.write(c)
continue
main()