73 lines
2.1 KiB
Java
73 lines
2.1 KiB
Java
import java.io.IOException;
|
|
import java.net.DatagramPacket;
|
|
import java.net.DatagramSocket;
|
|
import java.net.InetAddress;
|
|
import java.net.SocketException;
|
|
import java.net.UnknownHostException;
|
|
import java.util.ArrayList;
|
|
|
|
public class ChatApp {
|
|
|
|
/* Liste des utilisateurs actifs */
|
|
private ArrayList<Utilisateur> actifUsers ;
|
|
|
|
/* ChatApp est associé à un utilisateur */
|
|
private Utilisateur me;
|
|
|
|
public ChatApp(String pseudo, Integer port){
|
|
this.actifUsers = new ArrayList<Utilisateur>() ;
|
|
// Recuperer adresse IP de l'utilisateur
|
|
InetAddress ip = null ;
|
|
try {
|
|
ip = InetAddress.getLocalHost();
|
|
} catch (UnknownHostException e) {
|
|
e.printStackTrace();
|
|
}
|
|
//ip.getHostAddress();
|
|
this.me = new Utilisateur(pseudo,port,ip);
|
|
this.actifUsers.add(me);
|
|
}
|
|
|
|
public void connexion() throws IOException {
|
|
// Envoie en broadcast à tous les utilsateurs
|
|
DatagramSocket socket = new DatagramSocket();
|
|
socket.setBroadcast(true);
|
|
// @ de broadcast du réseau de l'utilisateur me
|
|
InetAddress broadcastAdress = this.me.getIp(); // A MODIFIER
|
|
// Message que l'on envoie à tous les utilisateurs actifs
|
|
String broadcastMessage = this.me.toString() ;
|
|
byte[]buffer = broadcastMessage.getBytes();
|
|
DatagramPacket packet = new DatagramPacket( buffer, buffer.length, InetAddress.getLoopbackAddress(), 1234 );
|
|
socket.send(packet);
|
|
socket.close();
|
|
System.out.println("Chat app -> " + broadcastMessage);
|
|
}
|
|
|
|
public static void main (String[] args) {
|
|
//Integer p = 2345 ;
|
|
ChatApp app = new ChatApp(args[0],Integer.parseInt(args[1])) ;
|
|
try {
|
|
app.connexion();
|
|
} catch (IOException e) {
|
|
e.printStackTrace();
|
|
}
|
|
DatagramSocket socket = null;
|
|
try {
|
|
socket = new DatagramSocket(1234);
|
|
} catch (SocketException e1) {
|
|
e1.printStackTrace();
|
|
}
|
|
byte buffer[] = new byte[1024];
|
|
while(true)
|
|
{
|
|
DatagramPacket data = new DatagramPacket(buffer,buffer.length);
|
|
try {
|
|
socket.receive(data);
|
|
} catch (IOException e) {
|
|
e.printStackTrace();
|
|
}
|
|
System.out.println(data);
|
|
}
|
|
}
|
|
|
|
}
|