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 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
| /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package chat_compris;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
/**
*
* @author othmane
*/
public class client1
{
public static void main(String[] args) throws IOException
{
// En-tête Ã* envoyer
String[] tab = {"Serveur1", "Serveur2","Serveur3", "Client"};
// Ouverture de la communication
Socket sock = new Socket(InetAddress.getLocalHost(),9001);
ObjectOutputStream out = new ObjectOutputStream(sock.getOutputStream());
// Envoi de l'en-tête
out.writeInt(tab.length);
for (int i=0; i<tab.length; i++)
out.writeUTF(tab[i]);
// Envoi du fichier
commun.transfert(
new FileInputStream(new File("C:\\M1\\oth.png")),
out,
true);
// Fermeture de la communication
sock.close();
}
}
classe serveur
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package chat_compris;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
/**
*
* @author othmane
*/
public class serveur1
{
public static void main(String[] args) throws IOException
{
// Ouverture d'une communication
Socket sock = new ServerSocket(9001).accept();
ObjectInputStream in = new ObjectInputStream(sock.getInputStream());
// Réception de l'en-tête
int n = in.readInt();
String[] tab = new String[n];
for (int i=0; i<n; i++)
tab[i]=in.readUTF();
// Réception du fichier
commun.transfert(
in,
new FileOutputStream(new File("C:\\M2\\f2.png")),
true);
// Fermeture de la communication
sock.close();
// Affichage de l'en-tête
for (String s : tab)
System.out.println(s);
}
}
classe comun
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package chat_compris;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
*
* @author othmane
*/
public class commun
{
public static void transfert(InputStream in, OutputStream out, boolean closeOnExit) throws IOException
{
byte buf[] = new byte[1024];
int n;
while((n=in.read(buf))!=-1)
out.write(buf,0,n);
if (closeOnExit)
{
in.close();
out.close();
}
}
} |
Partager