Simple use of Socket, socket

Source: Internet
Author: User

Simple use of Socket, socket

Client code:

import java.io.*;import java.net.*;public class DailyAdviceClient {    public void go(){        try{            Socket s=new Socket("127.0.0.1",4242);            InputStreamReader streamReader=new InputStreamReader(s.getInputStream());            BufferedReader reader=new BufferedReader(streamReader);                        String advice=reader.readLine();            System.out.println("Today you should: "+advice);            reader.close();        }        catch(IOException ex){            ex.printStackTrace();        }    }    public static void main(String[] args){        DailyAdviceClient client=new DailyAdviceClient();        client.go();    }}

Server code:

import java.io.*;import java.net.*;public class DailyAdviceServer {    String[] adviceList={"Take smaller bites","Go for the tight jeans.No they do NOT make you look fat.",    "One word:inappropriate","Just for oday,be honest.Tell your boss what you *really* think",    "You might want to rethink that haircut."};    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 ex){            ex.printStackTrace();        }    }    private String getAdvice(){        int random=(int)(Math.random()*adviceList.length);        return adviceList[random];    }    public static void main(String[] args){        DailyAdviceServer server=new DailyAdviceServer();        server.go();    }}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.