socket服务器端与客户端编程

1.服务器端

ServerSocket server = null;
  Socket socket = null;
  try {
   // 开启服务器端监听
   server = new ServerSocket(port);
   // 监听客户端连接
   socket = server.accept();
   // 读写
   BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
   PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
   String str = reader.readLine();
   while(str != null){
    out.println("received:" + str);
   }
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   try {
    socket.close();
    server.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }

2.客户端

 Socket socket = null;
   try {
   InetAddress address = InetAddress.getByName("localhost");
   socket = new Socket(address,port);
   BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
   PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()),true);
   writer.println("I am client");
   String string = reader.readLine();
   System.out.println(string);
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   try {
    socket.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }

相关推荐