所以我用python在套接字中创建了一个简单的服务器-客户端,我有一个问题是服务器不断从客户端返回双倍的字符串,有人可以帮助我吗?谢谢。
服务器:
def new_user(client,addr):
while True:
data = client.recv(10030)
client.settimeout(5.0)
if not data:
break
if data == ("-quit-"):
break
data = data.upper()
print("Client ->",data)
data = raw_input("Admin ->")
client.send(data)
client.close()
def main():
start_user()
def start_user():
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
print("Socket Telah Dibuat")
try:
s.bind(('',4303))
print("Bind telah dibuat")
except:
print("Bind failed"+str(sys.exc_info()))
sys.exit(1)
s.listen(1)
while True:
client , addr = s.accept()
print("Client telah connect:"+str(addr))
Thread(target=new_user,args=(client,addr)).start()
s.close()
客户:
def main():
s = socket.socket()
print("Socket Telah Dibuat")
try:
s.connect(('',4303))
print("telah connect")
except:
print("connection failed"+str(sys.exc_info()))
sys.exit(1)
print("Untuk Quit Masukkan--quit--:")
message = raw_input("->")
while message != ("--quit--"):
s.send(message)
data = s.recv(10030)
if not data:
break
data = data.upper()
print("Admin ->",data)
message = raw_input("->")
s.send(message)
s.close()
('Client ->', 'HELLO')-- from here
Admin ->yes
('Client ->', 'WHAT UP')
Admin ->yo too
('Client ->', 'WHAT UP')
Admin ->what -- to here is still working
('Client ->', 'LETS MEET UPLETS MEET UP') <--this where its start to get error
Socket Telah Dibuat
telah connect
Untuk Quit Masukkan--quit--:
->hello
('Admin ->', 'YES')
->what up
('Admin ->', 'YO TOO')
->lets meet up
('Admin ->', 'WHAT ')
答案 0 :(得分:1)
也许您可以更改为:
message = ""
while message != ("--quit--"):
message = raw_input("->")
s.send(message)
data = s.recv(10030)
if not data:
break
data = data.upper()
print("Admin ->",data)
答案 1 :(得分:0)
客户端发送了两次消息。
while message != ("--quit--"):
s.send(message) // HERE
data = s.recv(10030)
if not data:
break
data = data.upper()
print("Admin ->",data)
message = raw_input("->")
s.send(message) // AND HERE