client端socket
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(); } }
服务端ide
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(); } } }