[英]Concurrent read/write of named pipe in Java (on windows)
我正在嘗試使用命名管道在Windows上提供C#應用程序和Java應用程序之間的通信,該管道使用v01ver在此問題中描述的方法: 如何從Java打開Windows命名管道?
我在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();
}
輸出是:
Writing a message...然后它會永遠等待。
如何在另一個線程中等待輸入時寫入命名管道?
這是管道的預期行為。 它應該掛起,直到其他進程連接到管道並讀取它。
我想這里的RandomAccessFile
不是正確的API。 在Java端嘗試FileInputStream + FileOutputStream。 但這只是一個猜測,因為我最近在命名管道尚不存在的時候使用過Windows API。
我有同樣的問題 - 使用命名管道在C#/ Python應用程序和Windows上的Java應用程序之間進行通信:
我們String echoResponse = pipe.readLine();
Java編寫的客戶端代碼示例,但是在行中String echoResponse = pipe.readLine();
踩等待永遠。
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
訪問命名管道是正確的。 命名管道是文件系統對象。 在Linux / Unix下,它也被稱為“fifo”。 這些對象就像文件一樣可讀。 (與Java Pipe類抽象的進程之間使用的管道不同)。
但是我發現你的程序存在兩個問題。 我目前無法測試它,因為我需要你的測試服務器(隨意發布)。 您的讀者線程等待來自另一方(即服務器)的答案。 它使用readLine(),我會使用不同的方法(通過char調試char可能是最好的)。
使用Java(沒有JNI),您實際上無法創建命名管道(服務器端)。 使用RandomAccessFile使用的泛型方法打開命名管道,您將獲得一個字節類型的流,可以是單向或雙向的。
BTW:JTDS(SQL Server的免費JDBC驅動程序)可以選擇使用命名管道訪問SQL服務器,甚至可以通過網絡訪問。 它正在使用RandomAccessFile
方法。
BTW2:舊的MS SQL Server安裝媒體上有一個makepipe.exe測試服務器,但是我沒有找到可靠的來源來獲取該文件。
我對JAVA並不熟悉,而且我的C#也非常基礎。 但是我遇到了類似的多線程C ++客戶端問題,我通過打開重疊IO管道來解決這個問題。 直到我這樣做,Windows序列化讀取和寫入,有效地導致不滿意(阻塞)ReadFile,以防止在讀取完成之前完成后續的WriteFile。
請參見CreateFile函數
FILE_FLAG_OVERLAPPED
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.