我正在尝试使用 v01ver 在这个问题中描述的方法使用命名管道在 Windows 上提供 C# 应用程序和 Java 应用程序之间的通信:How to open a Windows named pipe from Java?
我在 Java 方面遇到了一个问题,因为我有一个读取器线程不断地等待管道上的输入,当我尝试从我的主线程写入管道时,它会永远卡住。
final RandomAccessFile pipe;
try {
pipe = new RandomAccessFile("\\\\.\\pipe\\mypipe", "rw");
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
return;
}
Thread readerThread = new Thread(new Runnable() {
@Override
public void run() {
String line = null;
try {
while (null != (line = pipe.readLine())) {
System.out.println(line);
}
}
catch (IOException ex) {
ex.printStackTrace();
}
}
});
readerThread.start();
try { Thread.sleep(500); } catch (InterruptedException e) {}
try {
System.out.println("Writing a message...");
pipe.write("Hello there.\n".getBytes());
System.out.println("Finished.");
}
catch (IOException ex) {
ex.printStackTrace();
}
输出是:
正在写消息...然后它永远等待。
如何在等待另一个线程中的输入时写入命名管道?
这是管道的预期行为。它应该挂起,直到其他进程连接到管道并读取它。
我有同样的问题——C#/Python 应用程序和 Java 应用程序在 Windows 上使用命名管道进行通信:
我们有用 Java 编写的客户端代码的示例,但是在线
String echoResponse = pipe.readLine();
tread 永远等待。
try {
// Connect to the pipe
RandomAccessFile pipe = new RandomAccessFile("\\\\.\\pipe\\testpipe", "rw");
String echoText = "Hello word\n";
// write to pipe
pipe.write ( echoText.getBytes() );
// read response
String echoResponse = pipe.readLine();
System.out.println("Response: " + echoResponse );
pipe.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
问题解决: 我有一个从这里用 Python 编写的 ServerPipe 代码示例代码 - 命名管道: 并在 Python 2.6.6
上运行它from ctypes import *
PIPE_ACCESS_DUPLEX = 0x3
PIPE_TYPE_MESSAGE = 0x4
PIPE_READMODE_MESSAGE = 0x2
PIPE_WAIT = 0
PIPE_UNLIMITED_INSTANCES = 255
BUFSIZE = 4096
NMPWAIT_USE_DEFAULT_WAIT = 0
INVALID_HANDLE_VALUE = -1
ERROR_PIPE_CONNECTED = 535
MESSAGE = "Default answer from server\0"
szPipename = "\\\\.\\pipe\\mynamedpipe"
def ReadWrite_ClientPipe_Thread(hPipe):
chBuf = create_string_buffer(BUFSIZE)
cbRead = c_ulong(0)
while 1:
fSuccess = windll.kernel32.ReadFile(hPipe, chBuf, BUFSIZE,
byref(cbRead), None)
if ((fSuccess ==1) or (cbRead.value != 0)):
print chBuf.value
cbWritten = c_ulong(0)
fSuccess = windll.kernel32.WriteFile(hPipe,
c_char_p(MESSAGE),
len(MESSAGE),
byref(cbWritten),
None
)
else:
break
if ( (not fSuccess) or (len(MESSAGE) != cbWritten.value)):
print "Could not reply to the client's request from the
pipe"
break
else:
print "Number of bytes written:", cbWritten.value
windll.kernel32.FlushFileBuffers(hPipe)
windll.kernel32.DisconnectNamedPipe(hPipe)
windll.kernel32.CloseHandle(hPipe)
return 0
def main():
THREADFUNC = CFUNCTYPE(c_int, c_int)
thread_func = THREADFUNC(ReadWrite_ClientPipe_Thread)
while 1:
hPipe = windll.kernel32.CreateNamedPipeA(szPipename,
PIPE_ACCESS_DUPLEX,
PIPE_TYPE_MESSAGE |
PIPE_READMODE_MESSAGE
|
PIPE_WAIT,
PIPE_UNLIMITED_INSTANCES,
BUFSIZE, BUFSIZE,
NMPWAIT_USE_DEFAULT_WAIT,
None
)
if (hPipe == INVALID_HANDLE_VALUE):
print "Error in creating Named Pipe"
return 0
fConnected = windll.kernel32.ConnectNamedPipe(hPipe, None)
if ((fConnected == 0) and (windll.kernel32.GetLastError() ==
ERROR_PIPE_CONNECTED)):
fConnected = 1
if (fConnected == 1):
dwThreadId = c_ulong(0)
hThread = windll.kernel32.CreateThread(None, 0,
thread_func, hPipe, 0, byref(dwThreadId))
if (hThread == -1):
print "Create Thread failed"
return 0
else:
windll.kernel32.CloseHandle(hThread)
else:
print "Could not connect to the Named Pipe"
windll.kernel32.CloseHandle(hPipe)
return 0
if __name__ == "__main__":
main()
服务器启动后,您可以使用稍微修改过的 Java 客户端代码:
try {
// Connect to the pipe
RandomAccessFile pipe = new RandomAccessFile("\\\\.\\pipe\\mynamedpipe", "rw");
String echoText = "Hello world\n";
// write to pipe
pipe.write(echoText.getBytes());
//String aChar;
StringBuffer fullString = new StringBuffer();
while(true){
int charCode = pipe.read();
if(charCode == 0) break;
//aChar = new Character((char)charCode).toString();
fullString.append((char)charCode);
}
System.out.println("Response: " + fullString);
pipe.close();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
在 NetBeans 6.9.1 中运行良好
我想
RandomAccessFile
在这里不是正确的 API。在 Java 端尝试 FileInputStream + FileOutputStream。但这只是一个猜测,因为我上次使用 Windows API 是在命名管道还不存在的时候。
别担心,使用
RandomAccessFile
访问命名管道是正确的。命名管道是一个文件系统对象。在 Linux/Unix 下它也被称为“fifo”。这些对象就像文件一样可读。 (与 Java Pipe 类抽象的进程之间使用的管道不同)。
但是我发现你的程序有两个问题。我目前无法测试它,因为我需要您的测试服务器(请随意发布)。您的读者线程等待来自另一方(即服务器)的答案。它使用 readLine(),我会使用不同的方法(调试逐字符读取字符可能是最好的方法)。
使用 Java(没有 JNI),您实际上无法创建命名管道(服务器端)。使用 RandomAccessFile 使用的通用方法打开命名管道,您将获得一个字节类型的流,可以是单向的或双工的。
顺便说一句:JTDS(SQL Server 的免费 JDBC 驱动程序)可以选择使用命名管道访问 SQL Server,甚至可以通过网络访问。它正是使用
RandomAccessFile
方法。
BTW2:旧的 MS SQL Server 安装介质上有一个 makepipe.exe 测试服务器,但是我没有找到可信任的来源来获取该文件。
我对JAVA不熟悉,我的C#也很初级。但是,我通过打开重叠 IO 的管道来修复多线程 C++ 客户端时遇到了类似的问题。在我这样做之前,Windows 序列化读取和写入,有效地导致不满足(阻塞)的 ReadFile 以阻止后续 WriteFile 的完成,直到读取完成。
参见CreateFile函数
FILE_FLAG_OVERLAPPED