Eclipse中用两个控制台测试网络通信程序

论坛 期权论坛 脚本     
匿名技术用户   2020-12-28 15:36   11   0

服务器端:

//: JabberServer.java
// Very simple server that just
// echoes whatever the client sends.
package foo;

import java.io.*;
import java.net.*;

public class Server {
 // Choose a port outside of the range 1-1024:
 public static final int PORT = 8080;

 public static void main(String[] args) throws IOException {
  ServerSocket s = new ServerSocket(PORT);
  System.out.println("Started: " + s);
  try {
   // Blocks until a connection occurs:
   Socket socket = s.accept();
   try {
    System.out.println("Connection accepted: " + socket);
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    // Output is automatically flushed
    // by PrintWriter:
    PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),
      true);
    while (true) {
     String str = in.readLine();
     if (str.equals("END"))
      break;
     System.out.println("Echoing: " + str);
     out.println(str);
    }
    // Always close the two sockets...
   } finally {
    System.out.println("closing...");
    socket.close();
   }
  } finally {
   s.close();
  }
 }
}
客户端:

package foo;

//: JabberClient.java
// Very simple client that just sends
// lines to the server and reads lines
// that the server sends.
import java.net.*;
import java.io.*;

public class Client {
 public static void main(String[] args) throws IOException {
  // Passing null to getByName() produces the
  // special "Local Loopback" IP address, for542
  // testing on one machine w/o a network:
  InetAddress addr = InetAddress.getByName(null);
  // Alternatively, you can use
  // the address or name:
  // InetAddress addr =
  // InetAddress.getByName("127.0.0.1");
  // InetAddress addr =
  // InetAddress.getByName("localhost");
  System.out.println("addr = " + addr);
  Socket socket = new Socket(addr, Server.PORT);
  // Guard everything in a try-finally to make
  // sure that the socket is closed:
  try {
   System.out.println("socket = " + socket);
   BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
   // Output is automatically flushed
   // by PrintWriter:
   PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),
     true);
   for (int i = 0; i < 10; i++) {
    out.println("howdy " + i);
    String str = in.readLine();
    System.out.println(str);
   }
   out.println("END");
  } finally {
   System.out.println("closing...");
   socket.close();
  }
 }
}


运行时发现需要两个控制台Console来分别显示:点击 图中 open console -- new console view 就会出现两个控制台了



然后将控制台拖出,方便同时查看,然后在程序运行完成后击 display selected console 来选择要显示的控制台视图



分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP