client端

public class WeatherClient{

    public static void main(String[] args) throwsUnknownHostException, IOException{

        //1.创建Socket对象,和服务端建立连接

        Socket socket = newSocket("127.0.0.1",12345);

        //2.发送城市名称

        DataOutputStream dos = newDataOutputStream(socket.getOutputStream());

        dos.writeUTF("北京");

        System.out.println("请求查询天气: 北京");

        //3.接受返回结果使用输入流

        DataInputStream dis = newDataInputStream(socket.getInputStream());

        String result = dis.readUTF();

        System.out.println("北京的天气: "+ result);

        //4.关闭流

        dis.close();

        dos.close();

    }

}

服务端

public class WeatherServer{
 
    public static void main(String[] args) throws IOException{
 
        // 1.创建ServerSocket对象
        ServerSocket serverSocket = new ServerSocket(12345);
 
        while(true){
 
            // 2.等待客户端连接,阻塞的方法
            final Socket socket = serverSocket.accept();
             
            Runnable runnable = new Runnable(){
                @Override
                public void run(){
                    try{
                        // 3.使用输入流接受客户端发送的请求
                        DataInputStream dis = new DataInputStream(socket.getInputStream());
                        String cityName = dis.readUTF();
                        System.out.println("接收到客户端发送的请求: " + cityName);
                         
                        Thread.sleep(1000);
                         
                        // 4.根据城市名查询天气
                        String result = "今天天气很热";
                        System.out.println("返回天气信息: " + result);
 
                        // 5.返回查询结果,使用输出流。
                        DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
                        dos.writeUTF(result);
 
                        // 6.关闭流
                        dis.close();
                        dos.close();
                    }catch(Exception e){
                        e.printStackTrace();
                    }
                }
            };
             
            //启动线程
            new Thread(runnable).start();
             
        }
    }
}

你若安好便是晴天
82 声望10 粉丝

引用和评论

0 条评论