Java Socket не привязывается к компьютеру Apple SiliconJAVA

Программисты JAVA общаются здесь
Anonymous
Java Socket не привязывается к компьютеру Apple Silicon

Сообщение Anonymous »

Я экспериментировал со связью с библиотеками Java Socket и DataStream. Я использую 2 файла: клиент и сервер. Я запускаю Сервер в одном окне терминала, а затем подключаюсь к нему с помощью Клиента на отдельном терминале. Клиент отправляет сообщения на сервер, а сервер их распечатывает. Они оба выходят, когда Клиент набирает «Over». Когда я использовал localhost на своем компьютере, все работало отлично, но когда я отправил файл клиента своему другу на машине с Windows и попросил его подключиться к моему компьютеру, Apple Silicon MacBook, это выдало исключение

Код: Выделить всё

java.net.ConnectException
: Время ожидания соединения истекло: подключитесь

Насколько я могу судить, это означает, что сокет не может привязаться к IP-адресу/порту на моем компьютер. Я думал, что это будет проблема с моим IP-адресом, портом или брандмауэром. Учитывая настройки конфиденциальности и безопасности macOS, я думаю, что это может быть брандмауэр. Ниже перечислены два файла. Любые идеи или помощь будут очень признательны. Кроме того, я не использовал localhost (127.0.0.1) в файле клиента, я использовал свой фактический IP-адрес.
Client.java

Код: Выделить всё

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

public class Client {
private Socket socket;
private DataInputStream input;
private DataOutputStream output;
private String username;
private String message;
private static String address;
private static int port;

public Client(String address, int port) {

// begin the socket, input stream, and output stream
try {
socket = new Socket(address, port);
System.out.println("UPDATE: Socket started");

input = new DataInputStream(System.in);
System.out.println("UPDATE: Input Stream Started.");

output = new DataOutputStream(socket.getOutputStream());
System.out.println("UPDATE: Output Stream Started.");
} catch (IOException e) {
System.out.println("ERROR: An IO exception occured while attempting to start the socket and input/output streams.");
System.out.println(e);
} catch (Exception e) {
System.out.println("ERROR: An unknown exception occured while attemption to start the socket and input/output streams.");
System.out.println(e);
}

// get the user's username
try {
System.out.print("Enter a username: ");
username = input.readLine();
} catch (IOException e) {
System.out.println("ERROR: An IO exception occured while attempting to get your username.");
System.out.println(e);
}

message = "";

// send the message to the server
while (!message.equals("Over")) { // over is the stop word
try {
System.out.print(">");
message = input.readLine();
output.writeUTF(username + ": "  + message);
} catch (IOException e) {
System.out.println("ERROR: An IO exception occured while attemption to send a message");
System.out.println(e);
}
}

// close the socket, input stream, and output stream
try {
input.close();
output.close();
socket.close();
} catch (IOException e) {
System.out.println("An IO exception occured while attemption go close the socket and input/output streams.");
System.out.println(e);
}
}

public static void main(String[] args) {
address = "127.0.0.1";
port = 9000;
Client client = new Client(address, port);
}
}
Server.java

Код: Выделить всё

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

public class Server {

private Socket socket;
private ServerSocket serverSocket;
private DataInputStream input;
private static int port;

public Server(int port) {

try {
serverSocket = new ServerSocket(port);
System.out.println("Server socket started.");

System.out.println("Waiting for client connection...");

socket = serverSocket.accept();
System.out.println("Client connection achieved");

input = new DataInputStream(new BufferedInputStream(socket.getInputStream()));

String line = "";

while (!line.equals("Over")) {
try {
line = input.readUTF();
System.out.println(line);
} catch (IOException e) {
System.out.println("An IO exception occured while recieving a message.");
System.out.println(e);
System.exit(1);
}
}

System.out.println("Closing connection");

socket.close();
input.close();
} catch (IOException e) {
System.out.println("An IO exception occured.");
System.out.println(e);
}
}

public static void main(String[] args) {
port = 9000;
Server server = new Server(port);
}
}
Я и мой друг пытались изменить порт, но это не сработало. Я не знаю, что еще я могу сделать.


Подробнее здесь: https://stackoverflow.com/questions/788 ... n-computer

Вернуться в «JAVA»