我正在使用python并尝试构建简单的服务器和客户端,客户端发送数据(一个接一个地按摩),服务器回复按摩(但用“hello”一词)
问题在于,当我尝试运行服务器时,它会自动完成...
服务器代码:
import socket
IP_ADDRESS, PORT = "127.0.0.1", 3016
def main():
connect()
def connect():
server_socket = socket.socket()
server_socket.bind((IP_ADDRESS, PORT))
server_socket.listen(1)
while True:
client_socket, client_address = server_socket.accept()
client_socket.send("Welcome!")
request = ""
try:
while request != "EXIT":
request = client_socket.recv(1024)
client_socket.send("hello")
except Exception, e:
client_socket.send("Error:" + e.message)
client_socket.close()
server_socket.close()
main()
客户代码:
import socket
IP_ADDRESS, PORT = "127.0.0.1", 3016
def main():
client_socket = socket.socket() # creating tcp socket
client_socket.connect((IP_ADDRESS, PORT))
print client_socket.recv(1024) # welcome massage
request = ""
while True:
request = raw_input("Enter request: ")
client_socket.send(request)
answer = client_socket.recv(1024)
print answer
if "Error" in answer:
break
client_socket.close()
main()