我已经建立了一个树莓皮3,我想做一个程序,发送数据时,每当一个按钮被按下我的试验板。我有一个运行在RPi上的Python服务器和一个运行在Windows笔记本上的Java客户机。但是,每当我向Java客户机发送数据时,它都会收到数据,然后由于某种原因,RPi服务器由于“管道中断”而关闭程序。但是这不可能是真的,因为我的Java程序从Pi接收数据!然后,由于Pi服务器关闭,Java程序关闭。但是从我在网上读到的,Python的“error32:breakepipe”是在远程套接字过早关闭时触发的!你知道吗
这是怎么回事?为什么我不能保持我的服务器运行?你知道吗
(PS:我的Java程序接收到的数据是错误的,但它仍然接收到数据。我发送“1\n”,然后接收null
。)
以下是我的RPi服务器程序的代码:
import RPi.GPIO as GPIO
from time import sleep
import atexit
import socket
import sys
GPIO.setmode(GPIO.BOARD)
GPIO.setup(5, GPIO.IN)
GPIO.setup(7, GPIO.OUT)
def cleanup():
print("Goodbye.")
s.close()
GPIO.cleanup()
atexit.register(cleanup)
THRESHOLD= 0.3
host= sys.argv[1]
port= 42844
length= 0
def displayDot():
GPIO.output(7,True)
sleep(0.2)
GPIO.output(7,False)
def displayDash():
GPIO.output(7,True)
sleep(0.5)
GPIO.output(7,False)
try:
print("Initializing connection...")
s= socket.socket(socket.AF_INET,socket.SOCK_STREAM)
serverAddress= (host, 42844)
s.bind(serverAddress)
print("Connection initialized!")
print("Waiting for client...")
s.listen(1) #Puts the server socket into server mode
client, address= s.accept()
print(address)
while True:
if not GPIO.input(5):
length+= 0.1
GPIO.output(7,True)
s.sendall('1\n')
print("HELLO??")
else:
if length!=0:
if length>=THRESHOLD:
print("Dash") #displayDash()
else:
print("Dot") #displayDot()
s.sendall('0')
length= 0
GPIO.output(7,False)
except KeyboardInterrupt:
print("\nScript Exited.")
cleanup();
以下是Java客户端程序的代码:
import java.net.*;
import java.io.*;
public class MorseClient{
public static void main(String[] args) throws IOException{
String hostname= null; //Initialize
int portNumber= 0; //Initialize
try {
hostname= args[0];
portNumber= Integer.parseInt(args[1]);
}
catch(ArrayIndexOutOfBoundsException aiobe) {
System.err.println("ERROR. Please specify server address, and port number, respectively");
System.exit(1);
}
Socket redoSocket;
long initTime;
try(
Socket echoSocket= new Socket(hostname, portNumber);
PrintWriter out= new PrintWriter(echoSocket.getOutputStream(), true);
BufferedReader in= new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
BufferedReader stdin= new BufferedReader(new InputStreamReader(System.in));
){
redoSocket= echoSocket;
System.out.println("Connection made!");
String userInput= "";
//Order of priority
//Connection time= 0
//Latency= 0
//Bandwidth= 1
redoSocket.setPerformancePreferences(0,0,1);
//Optimizes reliability
redoSocket.setTrafficClass(0x04);
echoSocket.setKeepAlive(true);
String returned= "";
while(true){
returned= in.readLine();
System.out.println(returned);
if(!(returned.isEmpty())){
System.out.println(returned);
System.out.println("YEP");
}
System.out.println(returned);
if(returned==null){
System.out.println("HAHA");
System.out.println("Attempting to reconnect...");
redoSocket= new Socket(hostname,portNumber);
System.out.println(redoSocket.isConnected());
}
}
}
catch(Exception e){
if(e instanceof ConnectException || e instanceof SocketException || e instanceof NullPointerException)
System.err.println("Connection closed by server");
else
System.err.println(e.toString());
}
}
}
Pi服务器的输出为:
python ServerMorse.py 192.168.1.101
Initializing connection...
Connection initialized!
Waiting for client...
('192.168.1.14', 58067)
('192.168.1.14', 58067)
Traceback (most recent call last):
File "ServerMorse.py", in <module>
s.sendall('1\n')
File "/usr/lib/python2.7/socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 32] Broken pipe
Goodbye.
以及Java客户机的输出:
java MorseClient 192.168.1.101 42844
Connection made!
null
Connection closed by server
上帝啊,你为什么要写一个带插座的服务器?使用烧瓶。你知道吗
http://flask.pocoo.org/
而且,很确定s不应该发送所有的。应该是这样的:
下面是我曾经用套接字编写的服务器的一些示例代码..可能很有用:
(response_ok是我写的一个函数)
相关问题 更多 >
编程相关推荐