我想多次发送数据。我在服务器和客户端上有以下代码:
在服务器上:
import socket
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(14,GPIO.OUT)
GPIO.setup(15,GPIO.OUT)
serversocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host="10.168.1.50"
port=80
print(host)
print(port)
serversocket.bind((host,port))
serversocket.listen(5)
print('server started listening')
while 1:
(clientsocket,address)=serversocket.accept()
print("connection established from : ",address)
data=clientsocket.recv(1024).decode()
print(data)
if (data=='hai'):
GPIO.output(14,True)
GPIO.output(15,False)
print 'hello'
else:
GPIO.output(14,False)
GPIO.output(15,False)
clientsocket.send("data is sent".encode())
在客户端:
import socket
s = socket.socket()
host = "10.168.1.50"
port = 80
s.connect((host,port))
while True:
in_data=raw_input(" Enter data to be sent > ")
s.send(in_data.encode())
s.send('hai'.encode())
data = ''
data = s.recv(1024).decode()
print (data)
s.close
我发送第一个字符串,得到响应,但是当我发送第二个字符串时,它会挂起。 我该如何解决这个问题?
答案 0 :(得分:1)
这是有效的代码
在服务器上:
import socket
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(14,GPIO.OUT)
GPIO.setup(15,GPIO.OUT)
serversocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host="10.168.1.50"
port=80
print(host)
print(port)
serversocket.bind((host,port))
serversocket.listen(5)
print('server started listening')
(clientsocket,address)=serversocket.accept()
print("connection established from : ",address)
while 1:
data=clientsocket.recv(1024).decode()
print(data)
if (data=='hai'):
GPIO.output(14,True)
GPIO.output(15,False)
print 'hello'
else:
GPIO.output(14,False)
GPIO.output(15,False)
clientsocket.send("data is sent".encode())
在客户端:
import socket
s = socket.socket()
host = "10.168.1.50"
port = 80
s.connect((host,port))
try:
while True:
in_data=raw_input(" Enter data to be sent > ")
s.send(in_data.encode())
data = ''
data = s.recv(1024).decode()
print (data)
finally:
s.close()
答案 1 :(得分:0)
这是我的客户,它正在运作。
import socket
s = socket.socket()
host = "10.168.1.50"
port = 80
s.connect((host,port))
try:
while True:
in_data=raw_input(" Enter data to be sent > ")
s.send(in_data.encode())
s.send('hai'.encode())
data = ''
data = s.recv(1024).decode()
print (data)
finally:
s.close()