Last active
April 28, 2016 15:29
-
-
Save kzkn/c18359037942ad0bc8fb391e951639d9 to your computer and use it in GitHub Desktop.
子プロセスで開いているポートに親プロセスからconnectする
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.InputStream; | |
import java.io.OutputStream; | |
import java.net.InetSocketAddress; | |
import java.net.ServerSocket; | |
import java.net.Socket; | |
public class Child { | |
public static void main(String[] args) throws Exception { | |
try (ServerSocket sock = new ServerSocket()) { | |
sock.bind(new InetSocketAddress(41000)); | |
while (true) { | |
System.err.println("CHILD: accepting"); | |
try (Socket client = sock.accept()) { | |
InputStream i = client.getInputStream(); | |
byte[] buf = new byte[1024]; | |
int len = i.read(buf); | |
System.err.println("CHILD: receive message: " + new String(buf, 0, len)); | |
OutputStream o = client.getOutputStream(); | |
o.write("hi, i am client".getBytes()); | |
o.flush(); | |
} | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.IOException; | |
import java.io.InputStream; | |
import java.io.OutputStream; | |
import java.lang.ProcessBuilder.Redirect; | |
import java.net.InetSocketAddress; | |
import java.net.Socket; | |
public class Parent { | |
public static void main(String[] args) throws Exception { | |
String javahome = System.getProperty("java.home"); | |
String classpath = System.getProperty("java.class.path"); | |
ProcessBuilder pb = new ProcessBuilder(javahome + "/bin/java", "-cp", classpath, "Child"); | |
pb.redirectError(Redirect.INHERIT); | |
Process p = pb.start(); | |
try { | |
for (int i = 0; i < 10; ++i) { | |
try (Socket s = new Socket()) { | |
System.out.println("PARENT: connect, try " + (i + 1)); | |
try { | |
s.connect(new InetSocketAddress("localhost", 41000)); | |
} | |
catch (IOException e) { | |
if (i == 9) | |
throw e; | |
Thread.sleep(1000); | |
continue; | |
} | |
OutputStream o = s.getOutputStream(); | |
o.write("i am parent".getBytes()); | |
o.flush(); | |
InputStream in = s.getInputStream(); | |
byte[] buf = new byte[1024]; | |
int len = in.read(buf); | |
System.out.println("PARENT: receive message: " + new String(buf, 0, len)); | |
break; | |
} | |
} | |
} | |
finally { | |
p.destroy(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment