Java 怎么侦听服务器上的连接

2019年7月5日21:45:18Java 怎么侦听服务器上的连接已关闭评论 465 980字阅读3分16秒

1.简介

Java 怎么侦听服务器上的连接?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class Main {
  static Socket socket = null;
  static PrintWriter out;
  static BufferedReader in;

  public static void main(String[] args) {
    try {
      socket = new Socket("127.0.0.1", 1234);
      
      out = new PrintWriter(socket.getOutputStream(), true);
      
      in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      testConnection();
      System.out.println("Closing the connection...");
      out.close();
      in.close();
      socket.close();
      System.exit(1);
    } catch (Exception e) {
      System.out.println(e);
      System.exit(1);
    }
  }

  public static void testConnection() {
    String serverResponse = null;
    if (socket != null && in != null && out != null) {
      System.out.println("Successfully connected, now testing...");

      try {
        
        out.println("Here is a test.");
        
        while ((serverResponse = in.readLine()) != null)
          System.out.println(serverResponse);
      } catch (IOException e) {
        System.out.println(e);
        System.exit(1);
      }
    }
  }
}

 
继续阅读
编程十万个怎么办