Я пытаюсь понять, как сокеты работают в Java, поэтому я хотел взглянуть на реализацию клиент-сервер.Я нашел это: Создание простого Java TCP / IP-сервера и клиентского сокета .
Сервер работает нормально, если я передал localhost
или 127.0.0.1
, однако клиент откажетсяподключиться к любому из них, выбрасывая исключение соединения, хотя я запустил сервер раньше клиента.
Вывод сервера:
Running Server: Host=127.0.0.1 Port=5069
Вывод клиента:
Exception in thread "main" java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at java.net.Socket.connect(Socket.java:538)
at java.net.Socket.<init>(Socket.java:434)
at java.net.Socket.<init>(Socket.java:244)
at Client.<init>(Client.java:12)
at Client.main(Client.java:29)
Мой код Java:
public class Server {
private ServerSocket server;
public Server(String ipAddress) throws Exception {
if (ipAddress != null && !ipAddress.isEmpty()) {
// System.out.println(InetAddress.getByName(ipAddress));
this.server = new ServerSocket(0, 1, InetAddress.getByName(ipAddress));
} else {
this.server = new ServerSocket(0, 1, InetAddress.getLocalHost());
}
}
private void listen() throws Exception {
String data = null;
Socket client = this.server.accept();
String clientAddress = client.getInetAddress().getHostAddress();
System.out.println("\r\nNew connection from " + clientAddress);
BufferedReader in = new BufferedReader(
new InputStreamReader(client.getInputStream()));
while ((data = in.readLine()) != null) {
System.out.println("\r\nMessage from " + clientAddress + ": " + data);
}
}
public InetAddress getSocketAddress() {
return this.server.getInetAddress();
}
public int getPort() {
return this.server.getLocalPort();
}
public static void main(String[] args) throws Exception {
Server app = new Server("localhost");
System.out.println("\r\nRunning Server: " +
"Host=" + app.getSocketAddress().getHostAddress() +
" Port=" + 50696);
app.listen();
}
}
public class Client {
private Socket socket;
private Scanner scanner;
private Client(InetAddress serverAddress, int serverPort) throws Exception {
this.socket = new Socket(serverAddress, serverPort);
this.scanner = new Scanner(System.in);
}
private void start() throws IOException {
String input;
while (true) {
input = scanner.nextLine();
PrintWriter out = new PrintWriter(this.socket.getOutputStream(), true);
out.println(input);
out.flush();
}
}
public static void main(String[] args) throws Exception {
// System.out.println( InetAddress.getByName("localhost"));
Client client = new Client(
InetAddress.getByName("127.0.0.1"), 50696);
System.out.println("\r\nConnected to Server: " + client.socket.getInetAddress());
client.start();
}
}