无法在java中将客户端连接到服务器

时间:2014-12-10 10:08:58

标签: java client server

我仍然是一个新手,而且我确信已经多次询问过这个问题了。 我在java中创建了一个客户端服务器工具,当它在同一台机器上运行时,它运行得很好。 但是,当我尝试在不同的计算机上运行客户端但在同一网络上运行时,它不会连接到服务器。 所以有人可以告诉我我可以尝试/做什么来纠正它。

感谢。

来自客户的

代码段:

serverIP = String.valueOf(InetAddress.getLocalHost().getHostAddress());
int Port = 5000;

.
.
.
try 
            {
                sock = new Socket(serverIP, Port);
                InputStreamReader streamreader = new InputStreamReader(sock.getInputStream());
                reader = new BufferedReader(streamreader);
                writer = new PrintWriter(sock.getOutputStream());
                writer.println(username +":"+ encPassword+":has connected"+":Connect"); // Displays to everyone that user connected.
                writer.flush(); // flushes the buffer
                isConnected = true; // Used to see if the client is connected.
            }
            catch (Exception ex) 
            {
                chatTextArea.append("Cannot Connect! Try Again. \n");
                System.err.println(ex.getMessage());
                usernameField.setEditable(true);
                pass.setEditable(true);
            }
        ListenThread();
.
.
.

public void ListenThread() 
{
     Thread IncomingReader = new Thread(new IncomingReader());
     IncomingReader.start();
}
来自服务器的

代码段:

public void run() 
    {
        clientOutputStreams = new ArrayList();
        onlineUsers = new ArrayList();  
        try 
        {
            ServerSocket serverSock = new ServerSocket(5000);
        while (true) 
            {
                // set up the server writer function and then begin at the same
                // the listener using the Runnable and Thread
                Socket clientSock = serverSock.accept();
                PrintWriter writer = new PrintWriter(clientSock.getOutputStream());
                clientOutputStreams.add(writer);
                // use a Runnable to start a 'second main method that will run
                // the listener
                Thread listener = new Thread(new ClientHandler(clientSock, writer));
                listener.start();
                outputPane.append("Got a connection. \n");
    } // end while
        } // end try
        catch (Exception ex)
        {
            outputPane.append("Error making a connection. \n");
        } // end catch
}

1 个答案:

答案 0 :(得分:0)

我认为您的问题是客户端仍然尝试连接到正在运行的计算机上:

serverIP = String.valueOf(InetAddress.getLocalHost().getHostAddress());

serverIP应获取远程计算机的值(最好使用某些配置)..