你好,
我正在使用命名管道将数据从 c++ 程序传输到 java 。
我的问题是我读到的每一行在每个字符之间都有一个空格(“”),例如:
Sent : 25343,398843292,55871844,492974923,-0.042,-0.022,2.474
Receive : 2 5 3 4 3 , 3 9 8 8 4 3 2 9 2 , 5 5 8 7 1 8 4 4 , 4 9 2 9 7 4 9 2 3 , - 0 . 0 4 2 , - 0 . 0 2 2 , 2 . 4 7 4
我的问题是为什么会发生这种情况,我该如何避免这种情况。
C++ 管道的代码:
#include "stdafx.h"
///// SERVER PROGRAM /////
#include <iostream>
#include <windows.h>
using namespace std;
int main(int argc, const char **argv)
{
wcout << "Creating an instance of a named pipe..." << endl;
// Create a pipe to send data
HANDLE pipe = CreateNamedPipe(
L"\\\\.\\pipe\\my_pipe", // name of the pipe
PIPE_ACCESS_DUPLEX, // 1-way pipe -- send only
PIPE_TYPE_BYTE, // send data as a byte stream
1, // only allow 1 instance of this pipe
100, // no outbound buffer
100, // no inbound buffer
0, // use default wait time
PIPE_ACCEPT_REMOTE_CLIENTS // use default security attributes
);
if (pipe == NULL || pipe == INVALID_HANDLE_VALUE) {
wcout << "Failed to create outbound pipe instance.";
// look up error code here using GetLastError()
system("pause");
return 1;
}
wcout << "Waiting for a client to connect to the pipe..." << endl;
// This call blocks until a client process connects to the pipe
BOOL result = ConnectNamedPipe(pipe, NULL);
if (!result) {
wcout << "Failed to make connection on named pipe." << endl;
// look up error code here using GetLastError()
CloseHandle(pipe); // close the pipe
system("pause");
return 1;
}
wcout << "Sending data to pipe..." << endl;
int i = 0 ;
for(i=0 ; i<100 ; i++){
Sleep(25);
// This call blocks until a client process reads all the data
const wchar_t *data = L"25343,398843292,55871844,492974923,-0.042,-0.022,2.474\n";
//const wchar_t *data = L"1,1,1,1,1,1,1\r\n";
DWORD numBytesWritten = 0;
result = WriteFile(
pipe, // handle to our outbound pipe
data, // data to send
wcslen(data) * sizeof(wchar_t), // length of data to send (bytes)
&numBytesWritten, // will store actual amount of data sent
NULL // not using overlapped IO
);
if (result) {
wcout << "Number of bytes sent: " << numBytesWritten << endl;
} else {
wcout << "Failed to send data." << endl;
// look up error code here using GetLastError()
}
}
// Close the pipe (automatically disconnects client too)
CloseHandle(pipe);
wcout << "Done." << endl;
system("pause");
return 0;
}
来自读取管道的java代码:
public void run() {
mIsOn = true;
RandomAccessFile pipe = null;
try {
pipe = new RandomAccessFile("\\\\.\\pipe\\my_pipe", "r");
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
// Main loop
while (mIsOn) {
String inData="";
try {
// Read from the pipe one line at a time
inData = pipe.readLine();
if (inData != null) {
System.out.println("Read from pipe :" + inData);//**Here it prints with spaces**
parseData(inData);
}
} catch (IOException e) {
e.printStackTrace();
}
}
// Close the pipe at the end
try {
pipe.close();
} catch (IOException e) {
e.printStackTrace();
}
}
** 如果您想知道 parseData() 中发生了什么然后不要,因为空格在 System.out 之前(从管道读取:“+数据)
提前致谢