JavaUnixDomainSockets(JUDS)提供了Java的方法用来访问Unixdomainsockets套接字。
示例代码:
packagecom.google.code.juds.test;importjava.io.IOException;importjava.io.InputStream;importjava.io.OutputStream;importcom.google.code.juds.*;publicclassTestUnixDomainSocket{publicstaticvoidmain(String[]args)throwsIOException{if(args.length!=1){System.out.println("usage:javaTestUnixDomainSocketsocketfilename");System.exit(1);}StringsocketFile=args[0];byte[]b=newbyte[128];//Testcase1.1:TestUnixDomainSocketClientwithastreamsocketUnixDomainSocketClientsocket=newUnixDomainSocketClient(socketFile,UnixDomainSocket.SOCK_STREAM);InputStreamin=socket.getInputStream();OutputStreamout=socket.getOutputStream();in.read(b);System.out.println("Textreceived:\""+newString(b)+"\"");Stringtext="[2]Hello!I'mtheclient!";out.write(text.getBytes());System.out.println("Textsent:"+"\""+text+"\"");socket.close();//Testcase1.2:TestUnixDomainSocketClientwithadatagramsocketsocket=newUnixDomainSocketClient(socketFile,UnixDomainSocket.SOCK_DGRAM);System.out.println("Provokeandcatchan"+"UnsupportedOperationException:");try{in=socket.getInputStream();}catch(UnsupportedOperationExceptione){System.out.println("UnsupportedOperationExceptionhasbeen"+"thrownasexpected.");}out=socket.getOutputStream();text="[3]Hello!I'mtheclient!";out.write(text.getBytes());System.out.println("Textsent:\""+text+"\"");socket.close();//Testcase2.1:TestUnixDomainSocketServerwithastreamsocketSystem.out.println("\nTest#2:TestUnixDomainSocketServer\nTestcase"+"2.1:TestUnixDomainSocketServerwithastreamsocket...");UnixDomainSocketServerssocket=newUnixDomainSocketServer(socketFile,UnixDomainSocket.SOCK_STREAM);in=ssocket.getInputStream();out=ssocket.getOutputStream();in.read(b);System.out.println("Textreceived:\""+newString(b)+"\"");text="[5]Hello!I'mtheserver!";out.write(text.getBytes());System.out.println("Textsent:"+"\""+text+"\"");ssocket.close();ssocket.unlink();//Testcase2.2:TestUnixDomainSocketServerwithadatagramsocketSystem.out.println("Testcase2.2:TestUnixDomainSocketServerwith"+"adatagramsocket...");ssocket=newUnixDomainSocketServer(socketFile,UnixDomainSocket.SOCK_DGRAM);System.out.println("Provokeandcatchan"+"UnsupportedOperationException:");in=ssocket.getInputStream();try{out=ssocket.getOutputStream();}catch(UnsupportedOperationExceptione){System.out.println("UnsupportedOperationExceptionhasbeen"+"thrownasexpected.");}in.read(b);System.out.println("Textreceived:\""+newString(b)+"\"");ssocket.close();ssocket.unlink();}}
评论