所以我只是进入 python 并尝试一些东西。首先,我正在创建一个服务器,它执行简单的操作,例如“GET”存储文本、“STORE”旧存储文本上的新文本以及“TRANSLATE”小写文本到大写。但我有几个问题。到目前为止,这是我的代码:
import socket
HOST = '' # Symbolic name meaning the local host
PORT = 24069 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
try:
s.bind((HOST, PORT))
except socket.error , msg:
print 'Bind failed. Error code: ' + str(msg[0]) + 'Error message: ' + msg[1]
sys.exit()
print 'Socket bind complete'
s.listen(1)
print 'Socket now listening'
while 1:
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
data = conn.recv(1024)
reply = 'OK...' + data
if not data: break
conn.send(data)
conn.close()
s.close()
要开始将客户端的文本更改为大写,根据我的其他编程知识,我假设我会将客户端的文本存储在一个变量中,然后在其上运行一个函数以将其更改为大写。python中有这样的功能吗?有人可以给我一个片段吗?
最后,我将如何在 python 中执行 GET 或 STORE 之类的操作?我最好的猜测是:
data = conn.recv(1024)
if data == GET: print text
if data == STORE: text = data #Not sure how to reference the text that the client has entered
非常感谢您的帮助!:)
注意自我:
import socket
HOST = '' # Symbolic name meaning the local host
PORT = 24069 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
try:
s.bind((HOST, PORT))
except socket.error , msg:
print 'Bind failed. Error code: ' + str(msg[0]) + 'Error message: ' + msg[1]
sys.exit()
print 'Socket bind complete'
s.listen(1)
print 'Socket now listening'
# Accept the connection
(conn, addr) = s.accept()
print 'Server: got connection from client ' + addr[0] + ':' + str(addr[1])
storedText = 'Hiya!'
while 1:
data = conn.recv(1024)
tokens = data.split(' ', 1)
command = tokens[0]
if command == 'GET':
print addr[0] + ':' + str(addr[1]) + ' sends GET'
reply = storedText
elif command == 'STORE':
print addr[0] + ':' + str(addr[1]) + ' sends STORE'
storedText = tokens[0]
reply = '200 OK\n' + storedText
elif command == 'TRANSLATE':
print addr[0] + ':' + str(addr[1]) + ' sends TRANSLATE'
storedText = storedText.upper()
reply = storedText
elif command == 'EXIT':
print addr[0] + ':' + str(addr[1]) + ' sends EXIT'
conn.send('200 OK')
break
else:
reply = '400 Command not valid.'
# Send reply
conn.send(reply)
conn.close()
s.close()