public class TcpServer {
public void run(int port) {
try (ServerSocket serverSocket = new ServerSocket(port)) {
System.out.println("Server is listening on port " + port);
while (true) {
Socket socket = serverSocket.accept();
System.out.println("[ " + socket.getInetAddress() + " ] client connected");
OutputStream output = socket.getOutputStream();
PrintWriter writer = new PrintWriter(output, true);
writer.println(new Date().toString());
InputStream input = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
System.out.println("###### msg : " + reader.readLine());
}
} catch (IOException ex) {
System.out.println("Server exception: " + ex.getMessage());
ex.printStackTrace();
}
}
}
public class TcpClient {
public void run(String hostname, int port, String data) {
try (Socket socket = new Socket(hostname, port)) {
OutputStream out = socket.getOutputStream();
out.write(data.getBytes());
InputStream input = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String time = reader.readLine();
System.out.println(time);
} catch (UnknownHostException ex) {
System.out.println("Server not found: " + ex.getMessage());
} catch (IOException ex) {
System.out.println("I/O error: " + ex.getMessage());
}
}
}