我寫一個使用線程池,這樣多個客戶端可以同時與服務器通信,發送命令給它的客戶機/服務器應用程序:使用線程池的客戶端/服務器連接?
但它不能正常工作,甚至有一個非常簡單的客戶端:
這裏是我的客戶:
if(args.length==0) {
host="127.0.0.1";
port=11111;
} else {
host=args[0];
String portString = args[1];
try {
port = Integer.parseInt(portString);
} catch(Exception e) {
e.printStackTrace();
port = 11111;
}
}
try {
System.out.println("Client connects to host=" + host + " port=" + port);
Socket skt = new Socket(host, port);//line 30 in the exception
BufferedReader myInput = new BufferedReader(new InputStreamReader(skt.getInputStream()));
PrintWriter myOutput = new PrintWriter(skt.getOutputStream(), true);
myOutput.println("Hello I am the Client!");
String buf=myInput.readLine();
System.out.println(buf + "=buf");
if(buf!=null) {
System.out.println("Client receives " + buf + " from the Server!");
buf=myInput.readLine();
System.out.println(buf);
}
myOutput.close();
myInput.close();
skt.close();
,但我得到:
客戶端連接到主機= 127.0.0.1端口= 11111 java.net.ConnectException:連接被拒絕:在以 java.net.DualStackPlainSocketImpl.socketConnect(來源不明) java.net.DualStackPlainSocketImpl.connect0(本機方法)在 java.net.AbstractPlainSocketImpl.doConnect(來源不明)連接在 java.net.AbstractPlainSocketImpl.connectToAddress(未知來源)在處 java.net.SocksSocketImpl.connect java.net.PlainSocketImpl.connect(未知來源) java.net.AbstractPlainSocketImpl.connect(未知源)(未知來源)在 java.net.Socket.connect(未知源)在 java.net.Socket.connect(未知源)在 java.net.Socket。(未知源)在 java.net.Socket。(Un在 client.Client.main(Client.java:30已知來源))//看評論的代碼
,所以我想我的服務器很可能是錯誤的,因爲我看不到它在客戶端:
ServerMain.java
public static void main(String[] args) {
try {
clientlistener = new ClientListener(server);
//serversocket = new ServerSocket();
} catch (IOException e) {
System.out.println("Could not listen on tcpPort: " + tcpPort);
e.printStackTrace();
System.exit(-1);
}
}
在這裏,我打開clientlistener用新
private static Server server = new Server();
並希望將其添加到ServerSocket的比對線程池:
public ClientListener(Server server) throws ServerException{
this.server=server;
try {
serverSocket = new ServerSocket(server.getTcpPort());
} catch (IOException e) {
throw new ServerException(e.getMessage());
}
System.out.println(String.format("Accepting new clients " +
"on %s", serverSocket.getLocalSocketAddress()));
}
/**
* Spawns new threads on incoming connection requests from clients.
* */
@Override
public void run() {
while(true){
try {
ClientCommunicator cc = new ClientCommunicator(serverSocket.accept(), pool);
threadPool.execute(cc);
clientComms.add(cc);
} catch (SocketException e) {
System.out.println(e.getMessage());
return;
} catch (IOException e) {
System.out.println(e.getMessage());
return;
}
}
}
的ClientCommunicator只是在命令行中讀取類。
我的問題是:
請告訴我wron我的socket連接?
我打開一個並從客戶端接受它?
我真的非常appreaciate你的答案!