DaytimeServer.java
package net.tcp.daytime;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
public class DaytimeServer {
public final static int DEFAULT_PORT = 13;
public static void main(String[] args) {
int port = 1001;
try {
ServerSocket server = new ServerSocket(port);
Socket connection = null;
while (true) {
try {
connection = server.accept();
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
Date now = new Date();
out.write(now.toString() + "\r\n");
out.flush();
connection.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (connection != null)
connection.close();
} catch (IOException e) {
}
}
}
} catch (IOException e) {
System.err.println(e);
}
}
}
DaytimeClient.java
package net.tcp.daytime;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class DaytimeClient {
public static void main(String[] args) {
String hostname = null;
if (args.length > 0) {
hostname = args[0];
} else {
hostname = "localhost";
}
try {
InetAddress theAddress = InetAddress.getByName(hostname);
Socket theSocket = new Socket(theAddress, 1001);
InputStream timeStream = theSocket.getInputStream();
StringBuffer time = new StringBuffer();
int c;
while ((c = timeStream.read()) != -1)
time.append((char) c);
String timeString = time.toString().trim();
System.out.println("It is " + timeString + " at " + hostname);
}
catch (UnknownHostException e) {
System.err.println(e);
} catch (IOException e) {
System.err.println(e);
}
}
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.