2009-12-17 4 views
0

Bon, alors j'essaie d'apprendre le langage client/serveur Java et je passe en revue le code du tutoriel comme suit. Quand je change "localhost" à mon IP il arrête de travailler cependant. S'il vous plaît aider.Impossible de se connecter à mon serveur lorsque je mets mon adresse IP en Java

Modifier: "127.0.0.1" semble fonctionner aussi, mais pas mon vrai IP.

/* 
* Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved. 
* 
* Redistribution and use in source and binary forms, with or without 
* modification, are permitted provided that the following conditions 
* are met: 
* 
* - Redistributions of source code must retain the above copyright 
*  notice, this list of conditions and the following disclaimer. 
* 
* - Redistributions in binary form must reproduce the above copyright 
*  notice, this list of conditions and the following disclaimer in the 
*  documentation and/or other materials provided with the distribution. 
* 
* - Neither the name of Sun Microsystems nor the names of its 
*  contributors may be used to endorse or promote products derived 
*  from this software without specific prior written permission. 
* 
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS 
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, 
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
*/ 

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

public class KnockKnockServer { 
    public static void main(String[] args) throws IOException { 

     ServerSocket serverSocket = null; 
     try { 
      serverSocket = new ServerSocket(4444); 
     } catch (IOException e) { 
      System.err.println("Could not listen on port: 4444."); 
      System.exit(1); 
     } 

     Socket clientSocket = null; 
     try { 
      clientSocket = serverSocket.accept(); 
     } catch (IOException e) { 
      System.err.println("Accept failed."); 
      System.exit(1); 
     } 

     PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); 
     BufferedReader in = new BufferedReader(
       new InputStreamReader(
       clientSocket.getInputStream())); 
     String inputLine, outputLine; 
     KnockKnockProtocol kkp = new KnockKnockProtocol(); 

     outputLine = kkp.processInput(null); 
     out.println(outputLine); 

     while ((inputLine = in.readLine()) != null) { 
      outputLine = kkp.processInput(inputLine); 
      out.println(outputLine); 
      if (outputLine.equals("Bye.")) 
       break; 
     } 
     out.close(); 
     in.close(); 
     clientSocket.close(); 
     serverSocket.close(); 
    } 
} 


/* 
* Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved. 
* 
* Redistribution and use in source and binary forms, with or without 
* modification, are permitted provided that the following conditions 
* are met: 
* 
* - Redistributions of source code must retain the above copyright 
*  notice, this list of conditions and the following disclaimer. 
* 
* - Redistributions in binary form must reproduce the above copyright 
*  notice, this list of conditions and the following disclaimer in the 
*  documentation and/or other materials provided with the distribution. 
* 
* - Neither the name of Sun Microsystems nor the names of its 
*  contributors may be used to endorse or promote products derived 
*  from this software without specific prior written permission. 
* 
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS 
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, 
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
*/ 

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

public class KnockKnockClient { 
    public static void main(String[] args) throws IOException { 

     Socket kkSocket = null; 
     PrintWriter out = null; 
     BufferedReader in = null; 

     try { 
      kkSocket = new Socket("localhost", 4444); 
      out = new PrintWriter(kkSocket.getOutputStream(), true); 
      in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream())); 
     } catch (UnknownHostException e) { 
      System.err.println("Don't know about host: taranis."); 
      System.exit(1); 
     } catch (IOException e) { 
      System.err.println("Couldn't get I/O for the connection to: taranis."); 
      System.exit(1); 
     } 

     BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); 
     String fromServer; 
     String fromUser; 

     while ((fromServer = in.readLine()) != null) { 
      System.out.println("Server: " + fromServer); 
      if (fromServer.equals("Bye.")) 
       break; 

      fromUser = stdIn.readLine(); 
     if (fromUser != null) { 
       System.out.println("Client: " + fromUser); 
       out.println(fromUser); 
     } 
     } 

     out.close(); 
     in.close(); 
     stdIn.close(); 
     kkSocket.close(); 
    } 
} 

C'est l'erreur que j'obtiens.

java.net.ConnectException: Connection refused: connect 
    at java.net.PlainSocketImpl.socketConnect(Native Method) 
    at java.net.PlainSocketImpl.doConnect(Unknown Source) 
    at java.net.PlainSocketImpl.connectToAddress(Unknown Source) 
    at java.net.PlainSocketImpl.connect(Unknown Source) 
    at java.net.SocksSocketImpl.connect(Unknown Source) 
    at java.net.Socket.connect(Unknown Source) 
    at java.net.Socket.connect(Unknown Source) 
    at java.net.Socket.<init>(Unknown Source) 
    at java.net.Socket.<init>(Unknown Source) 
    at KnockKnockClient.main(KnockKnockClient.java:43) 
+1

Quand vous dites "arrête de travailler", que voulez-vous dire exactement? Est-ce qu'une exception est levée? Si oui, pouvez-vous poster un stacktrace? – Asaph

+0

Modifiez ce message d'erreur inutile pour imprimer l'exception réelle. Je me suis plaint à Sun il y a des années d'utiliser ces messages d'erreur stupides dans leurs tutoriels. Je pense qu'ils ont finalement réparé certains d'entre eux. Apparemment pas tous. – EJP

Répondre

2

Cela nécessitera des suppositions sauvages, mais voyons. Si vous utilisez Windows 7, notez que votre nom "localhost" peut être lié à l'adresse IPV6 de votre ordinateur au lieu de IPV4. Le fait que vous pouvez toujours y accéder à l'aide de 127.0.0.1 le montre bien.

Voir this question here.

Je dois ajouter: essayer « ping localhost » pour savoir quelle adresse IP il est lié. Et, si vous le pouvez, passez "0.0.0.0" comme l'adaptateur à lier dans le programme serveur, ce qui le forcera à IPV4.

+0

ping ip revient 127.0.0.1 – William

1

Vous devez également vérifier les paramètres du pare-feu de votre ordinateur. Il pourrait laisser le trafic localhost à travers, mais bloquer les autres adresses IP

0

Il y a peut-être deux ou trois choses qui se passent ici:

  1. le plus probable, votre ServerSocket obtient lié à une adresse IP locale (par exemple 0.0.0.0) et ServerSocket lie à l'adresse de port là; et ne répondrait à aucune requête provenant d'une adresse IP. Essayez new ServerSocket(4444, 50, InetAddress.getByAddress(new byte[] { YOU IP ADDRESS }).

  2. Vous pourriez avoir des demandes de blocage de pare-feu et autres.

+0

Je suis encore nouveau sur ce serveur client, alors où dois-je mettre cela? Le client ou le serveur? – William

+0

Quel est le format de VOTRE ADRESSE IP? J'ai essayé juste l'adresse, et cela n'a pas fonctionné, j'ai essayé XXX, XXX, XXX, XXX et cela n'a pas fonctionné eather. – William

+0

D'accord, je l'ai eu à travailler, mais maintenant je reçois ceci: java.net.BindException: ne peut pas attribuer adresse demandée: JVM_Bind \t à java.net.PlainSocketImpl.socketBind (Native Method) \t à java.net.PlainSocketImpl.bind (source inconnue) \t at java.net.ServerSocket.bind (source inconnue) \t at java.net.ServerSocket. (source inconnue) \t à KnockKnockServer.main (KnockKnockServer.java:40) – William

2

Vérifiez le fichier hosts dans C: \ Windows \ System32 \ drivers \ etc

Vous devriez avoir quelque chose d'entrée de gamme comme

127.0.0.1 localhost 

Dans certains cas, localhost peut être réglé à un autre valeur et cela provoquera une opération incorrecte.

netstat -a -n | find "LIST" 

Dans une boîte de dialogue, tous les programmes d'écoute et leurs ports seront affichés. Si le port est utilisé, vous le verrez ici.

Questions connexes