import java.net.*;
public class StartupEchoServer {
public static void main(String[] args) {
try { ServerSocket serverSocket =
new ServerSocket(
9080); System.out.println(
"EchoServer在9080端口上侦听......");
while (
true) { Socket socket = serverSocket.accept(); System.out.println(
"建立一个连接.../n");
new EchoServer(socket).start(); } }
catch (Exception e) { e.printStackTrace(); } }}
import java.io.*;
import java.net.*;
public class EchoClient {
public static void main(String[] args) { Socket socket =
null; BufferedReader in =
null; PrintWriter out =
null;
try { socket =
new Socket(
"localhost",
9080); in =
new BufferedReader(
new InputStreamReader(socket .getInputStream())); out =
new PrintWriter(socket.getOutputStream(),
true); out.println(
"DOW"); System.out.println(
"今天是:" + in.readLine()); out.println(
"DOY"); System.out.println(
"今天是一年的:" + in.readLine());
byte[] b =
new byte[
2048]; String msg =
new String(b,
0, System.in.read(b)); out.println(
"FREE:" + msg); System.out.println(
"收到答复:" + in.readLine()); }
catch (Exception e) { }
finally {
try {
if (in !=
null) in.close();
if (out !=
null) out.close();
if (socket !=
null) socket.close(); }
catch (Exception e1) { } } }}
import java.io.*;
import java.net.*;
import java.util.*;
public class EchoServer
extends Thread {
private Socket socket =
null;
public EchoServer(Socket s) {
this.socket = s; }
public void run() { BufferedReader in =
null; PrintWriter out =
null; Calendar c = Calendar.getInstance();
try { in =
new BufferedReader(
new InputStreamReader(
this.socket .getInputStream())); out =
new PrintWriter(
this.socket.getOutputStream(),
true);
do { String msg = in.readLine();
if (msg ==
null)
break; msg = msg.toUpperCase(); System.out.println(
"收到指令:" + msg);
if (msg.equals(
"DOW"))
switch (c.get(Calendar.DAY_OF_WEEK)) {
case Calendar.SUNDAY: out.println(
"SUNDAY");
break;
case Calendar.MONDAY: out.println(
"MONDAY");
break;
case Calendar.TUESDAY: out.println(
"TUESDAY");
break;
case Calendar.WEDNESDAY: out.println(
"WEDNESDAY");
break;
case Calendar.THURSDAY: out.println(
"THURSDAY");
break;
case Calendar.FRIDAY: out.println(
"FRIDAY");
break;
case Calendar.SATURDAY: out.println(
"SATURDAY"); }
if (msg.equals(
"DOY")) out.println(
"" + c.get(Calendar.DAY_OF_YEAR));
if (msg.startsWith(
"FREE")) out.println(msg.substring(
5)); }
while (
true); }
catch (Exception e) { }
finally {
try { System.out.println(
"关闭一个连接.../n");
if (in !=
null) in.close();
if (out !=
null) out.close();
if (
this.socket !=
null)
this.socket.close(); }
catch (Exception e3) { } } }}