Pages

Wednesday, January 20, 2010

Simple Daily Advise Server and Client

Daily Advice Server
****************

import java.io.*;
import java.net.*;

public class DailyAdviceServer {

    /**
     * @param args
     */
   
    String[] adviceList={"one server","two server","three server","four server","five server"
            ,"six server","seven server"};
   
    public void go()    {
        try    {
            ServerSocket serverSock=new ServerSocket(4242);
            while(true)    {
                Socket sock=serverSock.accept();
                PrintWriter writer=new PrintWriter(sock.getOutputStream());
                String advice=getAdvice();
                writer.println(advice);
                writer.close();
                System.out.println(advice);
            }
        }catch (IOException ioex){
            ioex.printStackTrace();
        }
    }
   
    public String getAdvice()    {
        int random=(int)(Math.random()*adviceList.length);
        return adviceList[random];
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        DailyAdviceServer server=new DailyAdviceServer();
        server.go();
    }

}

Daily Advice Client
****************

import java.io.*;
import java.net.*;

public class DailyAdviceClient {

    /**
     * @param args
     */
    public void go()    {
        try    {
            Socket socket=new Socket("127.0.0.1",4242);
           
            InputStreamReader streamReader=new InputStreamReader(socket.getInputStream());
            BufferedReader reader=new BufferedReader(streamReader);
           
            String advice=reader.readLine();
            System.out.println("Today you should: "+advice);
           
            reader.close();
           
        }    catch(IOException ioex)    {
            ioex.printStackTrace();
        }
    }
   
   
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        DailyAdviceClient client=new DailyAdviceClient();
        client.go();

    }

}

No comments:

Post a Comment