IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Entrée/Sortie Java Discussion :

java socket:problème de connection


Sujet :

Entrée/Sortie Java

  1. #1
    Membre du Club
    Inscrit en
    Octobre 2008
    Messages
    57
    Détails du profil
    Informations forums :
    Inscription : Octobre 2008
    Messages : 57
    Points : 42
    Points
    42
    Par défaut java socket:problème de connection
    Bonjour,
    je voudrais créer mon premier socket en java, mais cela ne fonctionne pas en fait j'ai une classe Echoserver1
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    import java.io.*;
    import java.net.*;
    public class EchoServer1 {
    	public static void main(String []args){
    //	if(args.length!=1){
    //		System.err.println("Aufruf:EchoClient<host>"+"<port>");
    //		System.exit(1);
    //	}
    	String host = "java EchoServer1";
    	int port = 5000;
    //	try{
    //		port = Integer.valueOf(args[1]).intValue();
    //	}
    //	catch (NumberFormatException e){
    //		System.err.println("ungueltige Portnummer");
    //		System.exit(1);
    //	}
    	try{
    		InetAddress addr = InetAddress.getLocalHost();
    		ServerSocket server = new ServerSocket(port);
    		System.out.println("EchoServer1 auf"+addr.getHostName()+" "+addr.getHostAddress()+" :"+port+"gestartet.....");
     
    			Socket client = server.accept();
    			InetAddress clientaddr = client.getInetAddress();
    			int clientport = client.getPort();
    			System.out.println("verbindung zu"+clientaddr.getHostAddress()+":"+clientport+"aufgebaut");
    			try{
    				BufferedReader sockin = new BufferedReader(new InputStreamReader(client.getInputStream()));
    				PrintWriter sockout= new PrintWriter(client.getOutputStream(),true);
     
    				String input;
    				while((input=sockin.readLine())!=null){
    					sockout.println("Antwort vom Server:"+input);
    				}
    			}
    			catch (IOException e){
    				System.err.println(e);
    			}
    			finally {
    				try{
    					if(client!=null) client.close();
    				}
    				catch (IOException e){
     
    				}
    				System.out.println("verbindung zu +"+clientaddr.getHostAddress()+":"+clientport+"abgebaut");
    			}
     
    	}
    	catch(Exception e){
    		System.err.println(e);
    	}
    }
    }
    et une classe client
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    import java.io.*;
    import java.net.*;
    public class EchoClient {
    public static void main (String []args){
    //	if(args.length!=2){
    //		System.err.println("Aufruf:EchoClient<host>"+"<port>");
    //		System.exit(1);
    //	}
    //	String host = "locahost";
    	int port = 1131;
    //	try{
    //		port = Integer.valueOf(args[1]).intValue();
    //	}
    //	catch (NumberFormatException e){
    //		System.err.println("ungueltige Portnummer");
    //		System.exit(1);
    //	}
    	Socket socket = null;
    	try {
    		socket = new Socket("localhost",port);
    		System.out.println("Local host:"+socket.getLocalAddress().getHostAddress());
    		System.out.println("Local port:"+ socket.getLocalPort());
    		System.out.println("Remote host:"+socket.getInetAddress().getHostAddress());
    		System.out.println("Remote port:"+socket.getPort());
     
    		BufferedReader sockin = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    		PrintWriter sockout = new PrintWriter(socket.getOutputStream(),true);
    		BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 
     
    		String input,str;
    		while(true){
    			System.out.print(">");
    			input = in.readLine();
    			if(input==null ||input.equals("q")) break;
     
    			sockout.print(input);
    			str=sockin.readLine();
    			System.out.println(str);
    		}
    	}
    	catch(Exception e){
    		System.err.println(e);
    	}
    	finally{
    		try{
    			if(socket!=null)socket.close();
     
    		}
    		catch (IOException e){
     
    		}
    	}
    }
    }
    Chaque fois que je compile j'ai un message d'erreur:java.net.ConnectException: Connection refused: connect
    apparemment la connection ne peut pas être établi je ne comprends pas pourquoi, tout semble en place

  2. #2
    Membre habitué
    Homme Profil pro
    Inscrit en
    Juin 2009
    Messages
    112
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 37
    Localisation : France, Gironde (Aquitaine)

    Informations forums :
    Inscription : Juin 2009
    Messages : 112
    Points : 136
    Points
    136
    Par défaut
    Salut,

    Chaque fois que je compile j'ai un message d'erreur:java.net.ConnectException
    Chaque fois que tu exécutes tu veux dire ?
    Il faut que ton port client et serveur soit le même si tu veux qu'ils puissent communiquer.
    "Je sais que je suis un geek depuis que j'utilise le timer de mIRC pour faire cuire des pâtes"

  3. #3
    Membre du Club
    Inscrit en
    Octobre 2008
    Messages
    57
    Détails du profil
    Informations forums :
    Inscription : Octobre 2008
    Messages : 57
    Points : 42
    Points
    42
    Par défaut
    merci ca marche,mais j'ai un soucis , mon serveur ne me retourne rien enfin presque rien. En fait si je saisi par exemple il devrait me retourner
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    Antwort vom Server:hallo
    cela ne fonctionne pas et par contre quand je saisi la connection n'est plus établi.Ai je fait une erreur dans ces codes? Cilent:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    while(true){
    			System.out.print(">");
    			input = in.readLine();
    			if(input==null ||input.equals("q")) break;
     
    			sockout.print(input);
    			str=sockin.readLine();
    			System.out.println(str);
    		}
    Server:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    while((input=sockin.readLine())!=null){
    					sockout.println("Antwort vom Server:"+input);
    				}
    Merci d'avance

  4. #4
    Membre émérite
    Avatar de gifffftane
    Profil pro
    Inscrit en
    Février 2007
    Messages
    2 354
    Détails du profil
    Informations personnelles :
    Localisation : France, Loire (Rhône Alpes)

    Informations forums :
    Inscription : Février 2007
    Messages : 2 354
    Points : 2 582
    Points
    2 582
    Par défaut
    Étant donné que tu lis ligne par ligne coté serveur, il faut aussi que tu écrives ligne par ligne coté client ; donc remplacer sockout.print(input) par sockout.println(input);.

    Et tu as de la chance que le println fasse le flush, mais fais-y gaffe à l'avenir, car cela ne tombe pas toujours aussi bien.
    Mieux que Google, utilisez Sur Java spécialisé sur la plate-forme java !
    Pour réaliser vos applications Java dans le cadre de prestations, forfait, conseil, contactez-moi en message privé.

  5. #5
    Membre du Club
    Inscrit en
    Octobre 2008
    Messages
    57
    Détails du profil
    Informations forums :
    Inscription : Octobre 2008
    Messages : 57
    Points : 42
    Points
    42
    Par défaut
    salut,
    avec print çà marche. j'ai essayé de pousser me recherches, alors j'ai écrit un server sur lequel plusieurs client peuvent simultanément se connecter( ca marche) , j'aimerai maintenant qu'un client ai la possibilité d'avoir le contenu d'un fichier sauvegardé dans le server( ca ne marche pas, je ne reçois aucune réponse du serveur

    voici mes classes

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    import java.io.BufferedOutputStream;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.InetAddress;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.net.UnknownHostException;
     
     
     
    public class Fileserver extends Thread {
    private Socket client;
    private File dir;
    private BufferedReader sockin;
    private BufferedOutputStream sockout;
    private String cmd;
    public Fileserver(Socket client, File dir){
    	this.client=client;
    	this.dir=dir;
     
    }
    public void run(){
    	InetAddress addr = client.getInetAddress();
    	int port = client.getPort();
    	System.out.println("Verbindung zu"+addr.getHostAddress()+":"+port+"aufgebaut");
    	try{
    		BufferedReader sockin = new BufferedReader(new InputStreamReader(client.getInputStream()));
    		PrintWriter sockout = new PrintWriter(client.getOutputStream(),true);
     
    		while((cmd=sockin.readLine())!=null){
    			if(cmd.equals("list")) doList();
    		}
    	}
    	catch(IOException e){
     
    	}
    	finally{
    		try{
    			if(client!=null)client.close();
    		}
    		catch(IOException e){
     
    		}
    		System.out.println("Verbindung zu"+addr.getHostAddress()+":"+port+"abgebaut");
    	}
    }
    private void doList()throws IOException{
    	String[]liste = dir.list();
    	String s;
    	for(int i=0;i<liste.length;i++){
    		File d = new File(dir,liste[i]);
    		if(d.isFile()){
    			s=liste[i]+"\t";
    			sockout.write(s.getBytes());
    			sockout.write('\n');
    			sockout.flush();
    		}
    	}
    }
    public static void main(String[]args){
    	int port = 5000;
    	String s = "C:\\Bilder";
    	File dir = new File(s);
    	if(!(dir.isDirectory())){
    		System.err.println(s+"ist kein verzeichnis");
    		System.exit(1);
    	}
    	try {
    		InetAddress addr = InetAddress.getLocalHost();
    		ServerSocket server = new ServerSocket(port);
    		System.out.println("FileServer auf"+addr.getHostAddress()+":"+port+"abgebaut");
    while(true){
    	new Fileserver(server.accept(), dir).start();
    }
    	} catch (IOException e) {
    		// TODO Auto-generated catch block
    		e.printStackTrace();
    	}
     
    }
    		}
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    import java.io.*;
    import java.net.*;
    public class FileClient {
    	private String host;
    	private int port;
    	private File dir;
    	private BufferedInputStream sockin;
    	private PrintWriter sockout;
    	private BufferedReader in;
    	private String cmd;
    	private static final String SEPARATOR=System.getProperty("line.separator");
     
    	public FileClient(String host,int port,File dir){
    		this.host=host;
    		this.port=port;
    		this.dir=dir;
    	}
    	public void doWork(){
    		Socket socket = null;
    		try {
    			socket = new Socket(host,port);
    	sockin = new BufferedInputStream(socket.getInputStream());
    	sockout = new PrintWriter(socket.getOutputStream(),true);
    	in = new BufferedReader(new InputStreamReader(System.in)); 
    	while(true){
    		System.out.print(">");
    		cmd=in.readLine();
    		if(cmd==null||cmd.equals("q"))
    		break;
    		if(cmd.equals("list"))doList();
    		else{
    			System.out.println("ungültiger Befehl");
    		}
    	}
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		finally{
    			if(socket!=null)
    				try {
    					socket.close();
    				} catch (IOException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
    		}
    	}
    	private void doList()throws IOException{
    		int c;
    		while((c=sockin.read())!=-1){
    			if(c=='\t') System.out.print(SEPARATOR);
    			else if ( c=='\n') break;
    			else System.out.print((char)c);
    		}
    	}
    	public static void main(String []args){
    		String host ="localhost";
    		int port =5000;
    		File dir = new File("C:\\Bilder");
    		if(!(dir.isDirectory())){
    			System.err.println("ist kein verzeichnis");
    			System.exit(1);
    		}
    		new FileClient(host, port, dir).doWork();
    	}
    	}
    Merci d'avance

  6. #6
    Membre du Club
    Inscrit en
    Octobre 2008
    Messages
    57
    Détails du profil
    Informations forums :
    Inscription : Octobre 2008
    Messages : 57
    Points : 42
    Points
    42
    Par défaut
    le problème apparamment se trouverai dans cette méthode:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    private void doList()throws IOException{
    		int c;
    		while((c=sockin.read())!=-1){
    			if(c=='\t') System.out.print(SEPARATOR);
    			else if ( c=='\n') break;
    			else System.out.print((char)c);
    		}
    	}

Discussions similaires

  1. [Java DB] Problème de connection
    Par FaridM dans le forum JDBC
    Réponses: 2
    Dernier message: 22/04/2009, 10h41
  2. Problème de connection à la BD Mysql via Java
    Par ferrari75k dans le forum JDBC
    Réponses: 25
    Dernier message: 21/01/2008, 23h41
  3. problème de connection java avec postgres
    Par jayfaze dans le forum JDBC
    Réponses: 3
    Dernier message: 22/01/2007, 23h46
  4. Problème de connection Socket Client
    Par xyz dans le forum Réseau
    Réponses: 27
    Dernier message: 12/04/2006, 15h13
  5. [SOCKET] Client C connecté à un serveur Java
    Par missllyss dans le forum Développement
    Réponses: 2
    Dernier message: 07/06/2004, 13h14

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo