我是一名初學者(正如您可能會說的那樣),並且在從我非常簡單的客戶端到我非常簡單的服務器之間建立連接時遇到問題。我的服務器啓動正常,因爲它創建了偵聽端口43594的serversocket。但是,當我運行我的客戶端嘗試建立連接時,我的客戶端嘗試連接時會拋出IOException。客戶端無法連接到服務器;拋出IOException。簡單的客戶端/服務器問題
我在業餘時間將java作爲一種業餘愛好,所以我非常感謝有人能幫助我理解發生了什麼事,我哪裏出錯了(或者如果我甚至可以在任何地方)以幫助我改進。
這裏是我的服務器代碼:
package src.org;
import java.io.FileInputStream;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.net.*;
import java.io.*;
public class Server {
private static final Logger logger = Logger.getLogger(Server.class.getName());
private final static void createSocket(int portNumber) throws IOException
{
ServerSocket serverSocket = new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
}
public static void main(String... args)
{
logger.info("Starting server...");
Properties properties = new Properties();
logger.info("loading settings...");
try
{
properties.load(new FileInputStream("settings.ini"));
Constants.GAME_NAME = properties.getProperty("name");
Constants.PORT = Integer.valueOf(properties.getProperty("port"));
} catch(Exception ex)
{
ex.printStackTrace();
}
logger.info("Creating sockets...");
try
{
logger.info("Socket created. Listening on port: " + Constants.PORT);
createSocket(Constants.PORT);
} catch(Exception ex)
{
logger.log(Level.SEVERE, "Error creating sockets.", ex);
System.exit(1);
}
}
}
其中(據我所知)似乎是在做自己的工作。
這裏就是我認爲是罪魁禍首類,客戶端類:
import java.io.*;
import java.net.*;
public class Client {
//private static final String hostName = Constants.HOST_NAME;
//private static final int portNumber = Constants.PORT;
private static final String hostName = "localhost";
private static final int portNumber = 43594;
public static void main(String... args)
{
try (
Socket socket = new Socket(InetAddress.getLocalHost(), portNumber); // using localhost at the moment
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
) {
System.out.println("Client socket created.");
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromServer, fromUser;
while((fromServer = in.readLine()) != null)
{
System.out.println("Server:" + fromServer);
fromUser = stdIn.readLine();
if(fromUser != null) {
System.out.println("Client: " + fromUser);
out.println(fromUser);
}
}
} catch(UnknownHostException ex) {
System.err.println("Unknown host: " + hostName);
System.exit(1);
} catch(IOException ioe) {
System.err.println("Couldn't get i/o from: " + hostName);
System.out.println("Error:" + ioe.getMessage());
System.exit(1);
}
}
}
當我ping本地主機我得到迴應;兩端的端口是43594,主機只在本地。來自客戶端的命令行的迴應是:
客戶端套接字創建 無法獲取的I/O:本地主機 錯誤:連接重置 按任意鍵繼續......
我對不起,我知道這對你們許多人來說是一個非常簡單的修復,但我似乎無法自己找到答案或修復它。任何見解或幫助將不勝感激。乾杯。
對不起,如果我遺漏了其他重要的信息。
是 - 聽起來很合理:) –