Socket java client serveur
Résoluvalour1234 Messages postés 70 Statut Membre -
je veux savoir si il y'a un moyen de créer un dossier et dans ce dossier un sous dossier, a partir du client dans la machine ou il y'a le serveur avec java .
je vous remercie.
- Socket java client serveur
- Jeux java itel - Télécharger - Jeux vidéo
- Cybera client - Télécharger - Divers Réseau & Wi-Fi
- Jeux java itel touche ✓ - Forum Mobile
- Serveur diff message ✓ - Forum Mobile
- Jeux java football - Télécharger - Jeux vidéo
34 réponses
- 1
- 2
La demande porte sur la création d’un dossier puis d’un sous-dossier via Java, à réaliser soit côté client soit côté serveur lors d’un échange réseau.
Plusieurs éléments évoqués décrivent des approches liées au transfert de fichiers et à l’utilisation de flux, notamment l’emploi de FileInputStream ou d’ObjectOutput/InputStream, avec write(byte[]) et read(byte[]).
Certains échanges portent aussi sur la structure du code, comme l’exigence d’une méthode main distincte ou des questions de portée des méthodes publiques ou static, et sur des remarques d’accès refusé à des chemins.
En cas de besoin utile, il faut noter que mélanger flux de fichiers et flux de communication peut compliquer le transfert, et que les solutions reposent sur des approches adaptées à chaque type d donnée.
Dans chacun des trois cas, on attend juste derrière le nom du fichier/dossier (un String)
Et dans les deux premiers on envoie dans la foulée le contenu par salves d'octets.
Si tu as un tel protocole respecté à la fois par le client et le serveur, c'est très facile de faire ce que tu veux, par exemple si le client veut créer le dossier "Toto" et le sous-dossier "Toto/Titi" :
Le client envoie [3,"Toto"] Le serveur reçoit [3,"Toto"] Le serveur créé le répertoire "Toto" Le client envoie [3,"Toto/Titi"] Le serveur reçoit [3,"Toto/Titi"] Le serveur créé le répertoire "Toto/Titi"
Il serait bien vu de faire des messages de confirmation pour informer le client si ça s'est bien passé ou non, mais là encore ce n'est qu'une question de protocole.
NB. J'ai une conception très personnelle de ce que je définis ici comme un "protocole", les puristes m'en voudront peut-être, mais si tu comprends l'idée c'est largement suffisant !
merci.
Vous n’avez pas trouvé la réponse que vous recherchez ?
Posez votre questionDe même, une fois qu'il aura vu que l'entier vaut 3, le serveur sait qu'il va devoir créer un fichier, donc il attend un String qui correspond au nom de ce dossier, String que va lui envoyer le client.
Cela se fait assez bien avec des ObjectOutputStream et ObjectInputStream
FileOutputStream fos = new FileOutputStream("c:\\dossier\\"+s);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeInt(12345);
oos.writeObject("Today");
et voici sur le serveur
FileInputStream fis = new FileInputStream("c:\\dossier\\"+s);
ObjectInputStream ois = new ObjectInputStream(fis);
merci
Client
public void Client(String s)
{
int in;
byte[] byteArray;
File fichier = null;
String cheminfichier= null;
String IP = "192.168.1.2";
try
{
Socket via = new Socket(IP, 1234);
if(via.isConnected())
{
JOptionPane.showMessageDialog(null, "connecté au serveur: " + IP);
JFileChooser selector = new JFileChooser();
selector.setDialogTitle("choisi le fichier");
int resulta = selector.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION)
fichier = selector.getSelectedFile();
cheminfichier = fichiergetPath().toString();
}
else
{via.close();}
String m=s; // c'est le string de la donnée de ma table SQL
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(cheminfichier));
BufferedOutputStream bos = new BufferedOutputStream(via.getOutputStream());
DataOutputStream dos = new DataOutputStream(via.getOutputStream());
dos.writeUTF(m);
byteArray = new byte[8192];
while ((in = bis.read(byteArray)) != -1)
{
bos.write(byteArray,0,in);
}
bis.close();
bos.close();
// ServerSocket.close();
// JOptionPane.showMessageDialog(null, "Le Fichier " + archivo.getName().toString() +
//" a bien été envoyé");
String oups=archivo.getName();
String nom=("/llego.msi/");
String gogle="//"+IP+nom+"\""+oups+"\"";
gogle1="//"+IP+nom+oups;
System.out.println(s);
jTextField6.setText(gogle);
jTextField3.setText(gogle1);
System.out.println(gogle);
System.out.println(s);
// String gogle= "\\"+"\\"+IP+nom+oups+""\t;
} catch (Exception e) {//JOptionPane.showMessageDialog(null,e,"Error",JOptionPane.ERROR_MESSAGE);
}
}
Le SERVEUR
package serveur;
import java.net.*;
import java.io.*;
import javax.swing.*;
class Servidor
{
public String user = System.getProperty("user.name");
public static String nom = System.getProperty("user.home");
public static void main (String[] args)
{
ServerSocket server;
Socket connection = null;
DataOutputStream output;
BufferedInputStream bis;
BufferedOutputStream bos;
byte[] receivedData;
int in = 0;
String file;
try{
server = new ServerSocket(1234);
while ( true ) {
connection = server.accept();
receivedData = new byte[8192];
bis = new BufferedInputStream(connection.getInputStream());
DataInputStream dis = new DataInputStream(connection.getInputStream());
//recibimos el nombre del fichero
file = dis.readUTF();
file = file.substring(file.indexOf('\\')+1,file.length());
File directorio = new File("c:\\dossier\\"+file+"\\");
directorio.mkdir();
bos = new BufferedOutputStream(new FileOutputStream("C:\\dossier\\"+ file));
while ((in = bis.read(receivedData)) != -1){
bos.write(receivedData,0,in);
}
bos.close();
dis.close();
// JOptionPane.showMessageDialog(null, "Fichier (" + file.toString() + ") Reçu");
// System.exit(0);
}
}catch (Exception e ) {
// JOptionPane.showMessageDialog(null,e, "Errror",JOptionPane.ERROR_MESSAGE);
}
}
}
Merci infiniment pour votre aide.
Je me demande donc où est passé notre discussion d'hier soir sur la mise en place d'un protocole de communication client/serveur !
merci .
Exemple :
ObjectInputStream in = new ObjectInputStream(connection.getInputStream());
int mode = in.readInt();
String nom = (String) in.readObject(); // nom de fichier ou répertoire
switch (mode)
{
case 1: // envoi de fichier
// ...
break;
case 2: // réception de fichier
// ...
break;
case 3: // création de répertoire
// ...
break;
}
Code Client
try
{
// IP = JOptionPane.showInputDialog(null,"Entrez Lip du pc distant","Cliente",JOptionPane.CANCEL_OPTION);
Socket via = new Socket(IP, 1234);
if(via.isConnected())
{
JOptionPane.showMessageDialog(null, "Connecté au Serveur: " + IP);
JFileChooser selector = new JFileChooser();
selector.setDialogTitle("Selecciona el archivo a enviar");
int resultado = selector.showOpenDialog(null);
if (resultado == JFileChooser.APPROVE_OPTION)
{
archivo = selector.getSelectedFile();
direccionArchivo = archivo.getPath().toString();
FileOutputStream fos = new FileOutputStream(direccionArchivo);
ObjectOutputStream oos = new ObjectOutputStream(fos);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(direccionArchivo));
oos.writeInt(1);
}
else{via.close();}
Code Serveur
package EspaceMateriels;
import java.net.*;
import java.io.*;
import javax.swing.*;
class Servidor
{
public String user = System.getProperty("user.name");
public static String nom = System.getProperty("user.home");
public static void main (String[] args)
{
ServerSocket server;
Socket connection = null;
DataOutputStream output;
BufferedInputStream bis = null;
BufferedOutputStream bos;
byte[] receivedData;
String file;
try{
server = new ServerSocket(1234);
while ( true ) {
connection = server.accept();
// bis = new BufferedInputStream(connection.getInputStream());
// DataInputStream dis = new DataInputStream(connection.getInputStream());
ObjectInputStream in = new ObjectInputStream(connection.getInputStream());
int mode = in.readInt();
String nom = (String) in.readObject(); // nom de fichier ou répertoire
switch (mode)
{
case 1:
receivedData = new byte[8192];
file = in.readUTF();
file = file.substring(file.indexOf('\\')+1,file.length());
//aqui se escribe el archivo en la ubicacion donde este el Servidor.jar
bos = new BufferedOutputStream(new FileOutputStream("C:\\llego.msi\\"+ file));
int in2;
while ((in2 = in.read(receivedData)) != -1){
bos.write(receivedData,0,in2);
}
bos.close();
break;
case 2:
break;
case 3: // création de répertoire
// ...
break;
}
//recibimos el nombre del fichero
//aqui se escribe el archivo en la ubicacion donde este el Servidor.jar
// JOptionPane.showMessageDialog(null, "Fichier (" + file.toString() + ") Reçu");
//// System.exit(0);
}
}catch (Exception e ) {
JOptionPane.showMessageDialog(null,e, "Errror",JOptionPane.ERROR_MESSAGE);
}
}
}
Merci infiniment pour ton aide.
Dans ton code client tu envoies 1 mais c'est tout, alors qu'il faudrait également envoyer le nom du fichier (là je pense que file=in.readUTF et nom=(String) in.readObject() font la même chose, donc un seul des deux suffira) puis le contenu du fichier avec write(byte[])
Au niveau du CLIENT
JFileChooser selector = new JFileChooser();
selector.setDialogTitle("Selecciona el archivo a enviar");
int resultado = selector.showOpenDialog(null);
if (resultado == JFileChooser.APPROVE_OPTION)
{
archivo = selector.getSelectedFile();
direccionArchivo = archivo.getPath().toString();
FileOutputStream fos = new FileOutputStream(direccionArchivo);
ObjectOutputStream oos = new ObjectOutputStream(fos);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(direccionArchivo));
---> DataOutputStream dos = new DataOutputStream(via.getOutputStream());
---> byteArray = new byte[8192];
---> dos.writeUTF(archivo.getName());
oos.writeInt(1);
while ((in = bis.read(byteArray)) != -1)
{
oos.write(byteArray,0,in);
}
}
else{via.close();}
Au nveau du serveur jai enlevé nom=(String) in.readObject() et laissé in.readUTF
merci KX pour vos réponses.
mais le probléme c'est qu'il ne fonctionne qu'une seul fois comme si le serveur se bloque voici mon code merci.
Code Serveur
package EspaceMateriels;
import java.net.*;
import java.io.*;
import javax.swing.*;
class Ser
{
public String user = System.getProperty("user.name");
public static String nom = System.getProperty("user.home");
public static void main (String[] args)
{
ServerSocket server;
Socket connection = null;
DataOutputStream output;
BufferedInputStream bis;
BufferedOutputStream bos;
byte[] receivedData;
int in;
String file;
try{
server = new ServerSocket(1234);
while ( true ) {
connection = server.accept();
receivedData = new byte[8192];
bis = new BufferedInputStream(connection.getInputStream());
DataInputStream dis = new DataInputStream(connection.getInputStream());
//recibimos el nombre del fichero
file = dis.readUTF();
file = file.substring(file.indexOf('\\')+1,file.length());
ObjectInputStream ois = new ObjectInputStream(connection.getInputStream());
// ois.skip(Long.MAX_VALUE);
int confirmation =(Integer) ois.readObject();
//aqui se escribe el archivo en la ubicacion donde este el Servidor.jar
bos = new BufferedOutputStream(new FileOutputStream("C:\\llego.msi\\"+ file));
if(confirmation==1)
{
File directorio = new File("c:\\ireg\\momo\\");
directorio.mkdirs();
// System.exit(0);
}
while ((in = bis.read(receivedData)) != -1){
bos.write(receivedData,0,in);
}
bos.close();
dis.close();
ois.close();
JOptionPane.showMessageDialog(null, "Fichier (" + file.toString() + ") Reçu");
// System.exit(0);
}
}catch (Exception e ) {
JOptionPane.showMessageDialog(null,e, "Errror",JOptionPane.ERROR_MESSAGE);
}
}
}
Code Client
try
{
// IP = JOptionPane.showInputDialog(null,"Entrez Lip du pc distant","Cliente",JOptionPane.CANCEL_OPTION);
Socket via = new Socket(IP, 1234);
if(via.isConnected())
{
JOptionPane.showMessageDialog(null, "Connecté au Serveur: " + IP);
JFileChooser selector = new JFileChooser();
selector.setDialogTitle("Selecciona el archivo a enviar");
int resultado = selector.showOpenDialog(null);
if (resultado == JFileChooser.APPROVE_OPTION)
{
archivo = selector.getSelectedFile();
direccionArchivo = archivo.getPath().toString();
}
else{via.close();}
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(direccionArchivo));
BufferedOutputStream bos = new BufferedOutputStream(via.getOutputStream());
//Enviamos el nombre del archivo
DataOutputStream dos = new DataOutputStream(via.getOutputStream());
dos.writeUTF(archivo.getName());
ObjectOutputStream oos = new ObjectOutputStream(via.getOutputStream());
oos.flush();
oos.writeObject(1);
byteArray = new byte[8192];
while ((in = bis.read(byteArray)) != -1)
{
bos.write(byteArray,0,in);
}
bis.close();
bos.close();
/*JOptionPane.showMessageDialog(null, "Le Fichier " + archivo.getName().toString() +
" a bien été envoyé");*/
String oups=archivo.getName();
String nom=("/IREG/");
String gogle="//"+IP+nom+"\""+oups+"\"";
gogle1="//"+IP+nom+oups;
jTextField6.setText(gogle);
jTextField5.setText(gogle1);
System.out.println(gogle);
// String gogle= "\\"+"\\"+IP+nom+oups+""\t;
}
}catch (Exception e) {//JOptionPane.showMessageDialog(null,e,"Error",JOptionPane.ERROR_MESSAGE);
}
}
je vous remercie beaucoup pour votre aide.
Serveur
package EspaceMateriels;
import java.net.*;
import java.io.*;
import javax.swing.*;
class Ser
{
public String user = System.getProperty("user.name");
public static String nom = System.getProperty("user.home");
public static void main (String[] args)
{
ServerSocket server;
Socket connection = null;
DataOutputStream output;
BufferedInputStream bis;
BufferedOutputStream bos;
byte[] receivedData;
int in;
String file;
try{
server = new ServerSocket(1234);
while ( true ) {
connection = server.accept();
receivedData = new byte[8192];
bis = new BufferedInputStream(connection.getInputStream());
DataInputStream dis = new DataInputStream(connection.getInputStream());
//recibimos el nombre del fichero
file = dis.readUTF();
file = file.substring(file.indexOf('\\')+1,file.length());
ObjectInputStream ois = new ObjectInputStream(connection.getInputStream());
// ois.skip(Long.MAX_VALUE);
int confirmation =(Integer) ois.readObject();
//aqui se escribe el archivo en la ubicacion donde este el Servidor.jar
bos = new BufferedOutputStream(new FileOutputStream("C:\\llego.msi\\"+ file));
if(confirmation==1)
{
File directorio = new File("c:\\llego.msi\\momo\\"+ file);
directorio.mkdirs();
// System.exit(0);
}
while ((in = bis.read(receivedData)) != -1){
bos.write(receivedData,0,in);
}
bos.close();
dis.close();
// ois.close();
JOptionPane.showMessageDialog(null, "Fichier (" + file.toString() + ") Reçu");
// System.exit(0);
}
}catch (Exception e ) {
JOptionPane.showMessageDialog(null,e, "Errror",JOptionPane.ERROR_MESSAGE);
}
}
}
Client
public void Cliente()
{
int in;
byte[] byteArray;
File archivo = null;
String direccionArchivo = null;
String IP = "127.0.0.1";
try
{
// IP = JOptionPane.showInputDialog(null,"Entrez Lip du pc distant","Cliente",JOptionPane.CANCEL_OPTION);
Socket via = new Socket(IP, 1234);
if(via.isConnected())
{
JOptionPane.showMessageDialog(null, "Connecté au Serveur: " + IP);
JFileChooser selector = new JFileChooser();
selector.setDialogTitle("Selecciona el archivo a enviar");
int resultado = selector.showOpenDialog(null);
if (resultado == JFileChooser.APPROVE_OPTION)
{
archivo = selector.getSelectedFile();
direccionArchivo = archivo.getPath().toString();
}
else{via.close();}
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(direccionArchivo));
BufferedOutputStream bos = new BufferedOutputStream(via.getOutputStream());
//Enviamos el nombre del archivo
DataOutputStream dos = new DataOutputStream(via.getOutputStream());
dos.writeUTF(archivo.getName());
ObjectOutputStream oos = new ObjectOutputStream(via.getOutputStream());
// oos.flush();
oos.writeObject(1);
byteArray = new byte[8192];
while ((in = bis.read(byteArray)) != -1)
{
bos.write(byteArray,0,in);
}
// bis.close();
// bos.close();
/*JOptionPane.showMessageDialog(null, "Le Fichier " + archivo.getName().toString() +
" a bien été envoyé");*/
String oups=archivo.getName();
String nom=("/IREG/");
String gogle="//"+IP+nom+"\""+oups+"\"";
gogle1="//"+IP+nom+oups;
jTextField6.setText(gogle);
jTextField5.setText(gogle1);
System.out.println(gogle);
// String gogle= "\\"+"\\"+IP+nom+oups+""\t;
}
}catch (Exception e) {//JOptionPane.showMessageDialog(null,e,"Error",JOptionPane.ERROR_MESSAGE);
}
}
Merci KX pour ton aide
C'est bien sûr incomplet, mais voici de quoi (re)commencer :
import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Serveur
{
private final ServerSocket srv;
private final File root;
public Serveur(File root, int port) throws IOException
{
srv = new ServerSocket(port);
this.root = root;
}
public void close() throws IOException
{
srv.close();
}
public void service() throws IOException
{
Socket clt = srv.accept();
ObjectOutputStream output = new ObjectOutputStream(clt.getOutputStream());
ObjectInputStream input = new ObjectInputStream(clt.getInputStream());
int mode = input.readInt();
switch (mode)
{
case 1 :
envoiFichier(input,output);
break;
case 2 :
receptionFichier(input,output);
break;
case 3 :
creationDossier(input,output);
break;
default :
envoiConfirmation(output,false,"Mode non reconnu.");
}
input.close();
output.close();
}
public boolean envoiFichier(ObjectInputStream input, ObjectOutputStream output) throws IOException
{
//TODO
envoiConfirmation(output,false,"Mode non implémenté.");
return false;
}
public boolean receptionFichier(ObjectInputStream input, ObjectOutputStream output) throws IOException
{
// TODO
envoiConfirmation(output,false,"Mode non implémenté.");
return false;
}
public boolean creationDossier(ObjectInputStream input, ObjectOutputStream output) throws IOException
{
String dir = input.readUTF();
String[] tab = dir.split("/\\\\");
File parent = root;
for (String child : tab)
parent = new File(parent,child);
try
{
boolean res = parent.mkdir();
envoiConfirmation(output,res,parent.getAbsolutePath());
return res;
}
catch (SecurityException e)
{
envoiConfirmation(output,false,e.toString());
return false;
}
}
public void envoiConfirmation(ObjectOutputStream output, boolean conf, String msg) throws IOException
{
output.writeBoolean(conf);
output.writeUTF(msg);
output.flush();
}
public static void main(String...args) throws IOException
{
Serveur s = new Serveur(new File("C:\\test\\"),1234);
for (int i=1; i<=3; i++)
s.service();
s.close();
}
}
import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
public class Client
{
public static final String user = System.getProperty("user.name");
public static final String nom = System.getProperty("user.home");
private final Socket clt;
private final ObjectInputStream input;
private final ObjectOutputStream output;
public Client(InetAddress address, int port) throws IOException
{
clt = new Socket(address,port);
output = new ObjectOutputStream(clt.getOutputStream());
input = new ObjectInputStream(clt.getInputStream());
}
public void close() throws IOException
{
input.close();
output.close();
clt.close();
}
public boolean envoiFichier(File fichier) throws IOException
{
// TODO
output.writeInt(1);
output.flush();
return receptionConfirmation();
}
public boolean receptionFichier(String nomFichier, File dst) throws IOException
{
// TODO
output.writeInt(2);
output.flush();
return receptionConfirmation();
}
public boolean creationDossier(String nomDossier) throws IOException
{
output.writeInt(3);
output.writeUTF(nomDossier);
output.flush();
return receptionConfirmation();
}
public boolean receptionConfirmation() throws IOException
{
boolean conf = input.readBoolean();
String msg = input.readUTF();
if (conf)
System.out.println("OK : "+msg);
else
System.err.println("KO : "+msg);
return conf;
}
public static void main(String...args) throws IOException
{
Client c1 = new Client(InetAddress.getLocalHost(),1234);
c1.creationDossier("tata");
c1.close();
Client c2 = new Client(InetAddress.getLocalHost(),1234);
c2.creationDossier("tata/toto");
c2.close();
Client c3 = new Client(InetAddress.getLocalHost(),1234);
c3.creationDossier("plop/titi");
c3.close();
}
}
- 1
- 2