Socket
这是一个通过s向自身发送数据的快速示例应用程序。
public class App {
private static final AtomicInteger port = new AtomicInteger(-1);
private static final AtomicBoolean read = new AtomicBoolean(true);
private static final class SocketReader implements Runnable {
@Override
public void run() {
try {
final ServerSocket serverSocket = new ServerSocket(0);
System.out.println("Connected on " + serverSocket);
synchronized (port) {
port.set(serverSocket.getLocalPort());
port.notifyAll();
}
while (read.get()) {
try (final Socket socket = serverSocket.accept()) {
final DataInputStream dis = new DataInputStream(socket.getInputStream());
System.out.println(dis.readDouble());
byte[] buffer = new byte[1024];
int numRead;
while ((numRead = dis.read(buffer)) != -1) {
System.out.print(new String(buffer, 0, numRead, "UTF-8"));
}
}
}
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
private static final class SocketWriter implements Runnable {
private final double d;
private final File file;
public SocketWriter(double d, File file) {
this.d = d;
this.file = file;
}
@Override
public void run() {
try {
while (port.get() < 1) {
synchronized (port) {
port.wait();
}
}
try (final Socket clientSocket = new Socket("localhost", port.get());
final DataOutputStream dos = new DataOutputStream(clientSocket.getOutputStream())) {
System.out.println(clientSocket);
dos.writeDouble(d);
try (final FileInputStream fis = new FileInputStream(file)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
dos.write(buffer, 0, bytesRead);
}
}
dos.flush();
}
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
public static void main(String[] args) throws InterruptedException {
final double d = 2.35;
final File f = new File(new File(System.getProperty("user.home"), "Downloads"), "readme.txt");
final ExecutorService executorService = Executors.newSingleThreadExecutor();
final Future<?> future = executorService.submit(new SocketReader());
new SocketWriter(d, f).run();
read.set(false);
executorService.shutdownNow();
try {
future.get();
} catch (ExecutionException ex) {
throw new RuntimeException(ex);
}
}
}
首先我们发送double
序列化文件,然后它在我的下载目录中发送一个随机文件的内容。
Thread
同时,另一个将所有这些都回显到控制台。