【发布时间】:2011-11-02 11:54:10
【问题描述】:
我有一个用 Java 编写的服务器和客户端的代码。但问题是如何在服务器运行时使用 Eclipse 在不同的控制台窗口上运行多个客户端?谢谢帮助! (解决了!!)
更新** 另一个问题:我将创建一个新问题
服务器:
import java.net.*;
import java.io.*;
public class ATMServer {
private static int connectionPort = 8989;
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
boolean listening = true;
try {
serverSocket = new ServerSocket(connectionPort);
} catch (IOException e) {
System.err.println("Could not listen on port: " + connectionPort);
System.exit(1);
}
System.out.println("Bank started listening on port: " + connectionPort);
while (listening)
new ATMServerThread(serverSocket.accept()).start();
serverSocket.close();
}
}
服务器线程:
import java.io.*;
import java.net.*;
public class ATMServerThread extends Thread {
private Socket socket = null;
private BufferedReader in;
PrintWriter out;
public ATMServerThread(Socket socket) {
super("ATMServerThread");
this.socket = socket;
}
public void run(){
}
}
}
客户:(**更新)
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class ATMClient {
private static int connectionPort = 8989;
public static void main(String[] args) throws IOException {
Socket ATMSocket = null;
PrintWriter out = null;
BufferedReader in = null;
String adress = "";
try {
adress = "127.0.0.1";
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("Missing argument ip-adress");
System.exit(1);
}
try {
ATMSocket = new Socket(adress, connectionPort);
out = new PrintWriter(ATMSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader
(ATMSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Unknown host: " +adress);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't open connection to " + adress);
System.exit(1);
}
out.close();
in.close();
ATMSocket.close();
}
【问题讨论】:
-
你试过什么?您将获得许多用于您将要启动的所有 Java 应用程序的控制台...
-
beny23 是对的。 Eclipse 应该会自动为您做到这一点。要查看不同的控制台,请单击您拥有的选项卡上的控制台按钮。您应该会看到所有打开的控制台。
-
当我尝试打开另一个控制台来运行客户端时,它并没有像我希望的那样单独运行。当我在第一个客户端控制台中写一些东西时,第一个和第二个都得到了输出。如何避免?
-
@Ferry 在 Eclipse 中按下运行按钮两次。
-
@Ferry 大概没有,但是您的服务器的代码丢失了。你确定你不只是被 eclispe 自动(默认)切换到产生输出的控制台弄糊涂了吗?
标签: java eclipse client-server