集册 Java实例教程 侦听服务器上的连接

侦听服务器上的连接

欢马劈雪     最近更新时间:2020-01-02 10:19:05

436
侦听服务器上的连接
/* 
*来 自
 NowJava.com - 时代Java
*/

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);/* from nowjava.com - 时代Java*/

      // Obtain a handle on the socket output

      out = new PrintWriter(socket.getOutputStream(), true);

      // Obtain a handle on the socket input

      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 {

        // Send data to server

        out.println(
展开阅读全文