/**
*
*/
package de.tutorials;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Semaphore;
/**
* @author Administrator
*
*/
public class SocketSynchronizer {
private Socket socket;
private Semaphore semaphore = new Semaphore(1);
private BufferedWriter bw;
/**
* @param args
*/
public static void main(String[] args) throws Exception {
new SocketSynchronizer().start();
}
private void start() throws Exception {
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
System.out.println("Shuting down...");
try {
if (bw != null) {
bw.close();
}
if (socket != null) {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
startServer(7777);
initSocket("localhost", 7777);
startClient("A");
startClient("B");
startClient("C");
}
private void startClient(String name) {
new Thread(name) {
public void run() {
while (true) {
try {
semaphore.acquire();
bw.write(this.getName());
bw.newLine();
bw.flush();
sleep(1000L + (long) (1000L * Math.random()));
semaphore.release();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}.start();
}
private void initSocket(String hostname, int port) throws Exception {
socket = new Socket(hostname, port);
bw = new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream()));
}
private void startServer(final int port) {
new Thread() {
public void run() {
try {
System.out.println("starting server @ " + port);
ServerSocket ss = new ServerSocket(port);
socket = ss.accept();
System.out.println("connected");
BufferedReader br = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
String line = null;
while ((line = br.readLine()) != null) {
System.out.print("received: ");
System.out.println(line);
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
}