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

2019年7月5日21:45:18 评论 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);
      }
    }
  }
}

 
展开全文
  • 版权所有:编程十万个怎么办
  • 转载注明:https://www.tah1986.com/12278.html
匿名

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: