What is wrong:
I am attempting to run two files; I first run the Server Main file, and then I run the Client Main file. I receive the error, "Connection refused" when I attempt to give "127.0.0.1" as the address.
Код: Выделить всё
package chatRoom2;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class ServerMain
{
ServersListener sl;
public static ArrayList oos = new ArrayList();
public static ArrayList ois = new ArrayList();
public static ArrayList sockets = new ArrayList();
public static void main(String[] args)
{
try
{
ServerSocket serverSocket = new ServerSocket(8000);
while(true)
{
Socket a = new Socket();
a = serverSocket.accept();
sockets.add(a);
ObjectOutputStream b = new ObjectOutputStream(a.getOutputStream());
ObjectInputStream c = new ObjectInputStream(a.getInputStream());
ServersListener sl = new ServersListener(c, b);
ObjectOutputStream os = new ObjectOutputStream(a.getOutputStream());
ObjectInputStream is = new ObjectInputStream(a.getInputStream());
Thread t = new Thread(new ServersListener(is,os));
t.start();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
package chatRoom2;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Scanner;
public class ClientMain
{
public static void main(String[] args)
{
try {
ChatRoomInfo info = new ChatRoomInfo(); //How should the infos communicate?
Scanner s = new Scanner(System.in);
System.out.println("Enter your name:");
String username = s.nextLine();
while (!ChatRoomInfo.nameIsAvailable(username))
{
System.out.println("Enter your name:");
username = s.nextLine();
}
System.out.println("Enter the ip address of the server:");
String address = s.nextLine();
s.close();
Socket socket = new Socket(address,8001);
ObjectInputStream is = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream os = new ObjectOutputStream(socket.getOutputStream());
System.out.println("Connected as " + username);
CommandFromServer cfs = (CommandFromServer) is.readObject();
ChatRoomFrame2 frame = new ChatRoomFrame2(os, username);
ClientsListener cl = new ClientsListener(is,os,frame);
Thread t = new Thread(cl);
t.start();
os.writeObject(new CommandFromClient(CommandFromClient.JOINED, username, ""));
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
If I input the name "Bob," after I type "127.0.0.1," the message, "Connected as Bob" should appear in the Console.
Inputting a name, "Enter your name:," proceeds correctly to "Enter the ip address of the server:." However, typing "127.0.0.1" led to the error "java.net.ConnectException: Connection refused."
I received the same "java.net.ConnectException: Connection refused" error after attempting to use the IP Address of my computer, which is different from the home address.
Источник: https://stackoverflow.com/questions/781 ... ng-refused
Мобильная версия