客户端代码:
importjava.io.*;importjava.net.*;publicclassDailyAdviceClient {publicvoidgo(){try{
Socket s=newSocket("127.0.0.1",4242);
InputStreamReader streamReader=newInputStreamReader(s.getInputStream());
BufferedReader reader=newBufferedReader(streamReader);
String advice=reader.readLine();
System.out.PRintln("Today you should: "+advice);
reader.close();
}catch(IOException ex){
ex.printStackTrace();
}
}publicstaticvoidmain(String[] args){
DailyAdviceClient client=newDailyAdviceClient();
client.go();
}
}
服务器代码:
importjava.io.*;importjava.net.*;publicclassDailyAdviceServer {
String[] adviceList={"Take smaller bites","Go for the tight jeans.No they do NOT make you look fat.","OneWord:inappropriate","Just for oday,be honest.Tell your boss what you *really* think","You might want to rethink that haircut."};publicvoidgo(){try{
ServerSocket serverSock=newServerSocket(4242);while(true){
Socket sock=serverSock.accept();
PrintWriter writer=newPrintWriter(sock.getOutputStream());
String advice=getAdvice();
writer.println(advice);
writer.close();
System.out.println(advice);
}
}catch(IOException ex){
ex.printStackTrace();
}
}privateString getAdvice(){intrandom=(int)(Math.random()*adviceList.length);returnadviceList[random];
}publicstaticvoidmain(String[] args){
DailyAdviceServer server=newDailyAdviceServer();
server.go();
}
}