在java中使用socket打印多行
我正在创建一个简单的客户端服务器,用于我的Raspberry Pi
我试图实现的是使用我的客户机向服务器发送“ACKTEMP”。然后,服务器调用串行端口(这是我的STM32 Nucleo Board btw),通过此消息,我使用串行通信获取温度,然后将其发送回客户端
我的问题是,NucleoBoard返回一些字符串,比如(TEMP:xx)。在我开始一次发送多个字符串之前,这一切都很正常。如果我发送ACKTEMP并希望接收(TEMP:xx)和“温度OK”,那么我只会得到第一行,即(TEMP:xx)
所以,在我的代码中,似乎有一个地方我需要修改一些东西,这样它就会打印出所有的行,而不是一行,然后停止。如果我的编程没有那么好,请不要生我的气。我是一名学生,试图理解一切
public class Client {
/**
* @param args the command line arguments
* @throws java.io.IOException
*/
public static void main(String[] args) throws IOException {
String sentence;
String messageFromServer;
while(true)
{
BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
try (Socket clientSocket = new Socket("192.168.0.135", 6789)) {
PrintWriter outToServer = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.println(sentence + '\n');
messageFromServer = inFromServer.readLine();
System.out.println("FROM SERVER: " + messageFromServer);
clientSocket.close();
}
}
}
}
public class Server {
private static SerialPort serialPort;
/**
* @param args the command line arguments
* @throws java.io.IOException
*/
public static void main(String[] args) throws IOException {
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(6789);
serialPort = new SerialPort("/dev/ttyACM0");
while(true)
{
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
PrintWriter outToClient = new PrintWriter(connectionSocket.getOutputStream(), true);
clientSentence = inFromClient.readLine();
try{
//opening port
serialPort.openPort();
serialPort.setParams(
SerialPort.BAUDRATE_115200,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
//Write string to port
serialPort.writeString(clientSentence + "\n");
System.out.println("String wrote to port, waiting for response..");
try {
Thread.sleep(10); //1000 milliseconds is one second.
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
String buffer = serialPort.readString();
outToClient.println(buffer + '\n');
serialPort.closePort();//Close serial port
}
catch(SerialPortException ex){
System.out.println("Error writing data to port: " + ex);
}
}
// TODO code application logic here
}
}
# 1 楼答案
我用以下方法解决了这个问题。但如果有人有更好的解决方案,这是非常受欢迎的
我所做的是,对于每一个我想要换行的字符串,我在我的NucleoSTM32程序中的字符串前面放一个“~”号