Application serveur

Fermé
sillaso
Messages postés
4
Date d'inscription
samedi 29 décembre 2012
Statut
Membre
Dernière intervention
29 décembre 2012
- 29 déc. 2012 à 19:07
KX
Messages postés
16540
Date d'inscription
samedi 31 mai 2008
Statut
Modérateur
Dernière intervention
22 mai 2022
- 29 déc. 2012 à 22:13
Bonsoir,
le problème c'est que l'application ne se ferme plus et il s'affiche en noir
voilà le code source
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashSet;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;


class Serveur extends JFrame implements ActionListener {
HashSet<String> names = new HashSet<String>();
private static HashSet<PrintWriter> writers = new HashSet<PrintWriter>();

private JPanel pan1, pan2,pan3;
private JLabel port,nbMax ;
private JTextField fport,fnbMax;
private JButton ecouter ;
ServerSocket serv ;
Serveur() {
setSize(460, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(new GridLayout(7, 1));
pan1 = new JPanel();
port = new JLabel("Port: " );
port.setPreferredSize(new Dimension(70, 30));
fport = new JTextField(15);
nbMax = new JLabel("Nombre maximum de clients : " );
nbMax.setPreferredSize(new Dimension(90, 30));
fnbMax = new JTextField(15);
pan1.add(port);
pan1.add(fport);
pan2 = new JPanel();
pan2.add(nbMax);
pan2.add(fnbMax);
pan3 = new JPanel();
ecouter = new JButton("Ecouter" );
pan3.add(ecouter);
Container c = getContentPane();
c.add(pan1); c.add(pan2); c.add(pan3);
ecouter.addActionListener(this);
}

@Override
public void actionPerformed(ActionEvent ae) {
String cmd=(String)ae.getActionCommand();
if(cmd.equals("Ecouter" ))
{int I1=Integer.parseInt(fport.getText());
int I2= Integer.parseInt(fnbMax.getText());

try{
serv = new ServerSocket(I1);

while(true){
ClientHandler w;

//server.accept returns a client connection
Socket soc=serv.accept();
PrintWriter writer = new PrintWriter(soc.getOutputStream());
writers.add(writer);
w = new ClientHandler(soc,writer);
Thread t = new Thread(w);
t.start();
}} catch (IOException e) {
}
finally {
try {
serv.close();
} catch (IOException ex) {
}
}
}


}

public class ClientHandler implements Runnable {
BufferedReader reader;
Socket sock;
PrintWriter client;


public ClientHandler(Socket clientSocket, PrintWriter user) {
// new inputStreamReader and then add it to a BufferedReader
client = user;
try {
sock = clientSocket;
InputStreamReader isReader = new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(isReader);
} // end try
catch (Exception ex) {
System.out.println("error beginning StreamReader" );
} // end catch

} // end ClientHandler()

public void run() {
String message;
String[] data;
String connect = "Connect";
String disconnect = "Disconnect";
String chat = "Chat";

try {
while ((message = reader.readLine()) != null) {

System.out.println("Received: " + message);
data = message.split("¥" );
for (String token:data) {

System.out.println(token);

}

if (data[2].equals(connect)) {

tellEveryone((data[0] + "¥" + data[1] + "¥" + chat));
userAdd(data[0]);

} else if (data[2].equals(disconnect)) {

tellEveryone((data[0] + "¥has disconnected." + "¥" + chat));
userRemove(data[0]);

} else if (data[2].equals(chat)) {

tellEveryone(message);

} else {
System.out.println("No Conditions were met." );
}


} // end while
} // end try
catch (Exception ex) {
System.out.println("lost a connection" );
writers.remove(client);
} // end catch
} // end run()
} // end class ClientHandler
public void userAdd (String data) {
String message;
String add = "¥ ¥Connect", done = "Server¥ ¥Done";
names.add(data);
String[] tempList = new String[(names.size())];
names.toArray(tempList);

for (String token:tempList) {

message = (token + add);
tellEveryone(message);
}
tellEveryone(done);
}

public void userRemove (String data) {
String message;
String add = "¥ ¥Connect", done = "Server¥ ¥Done";
names.remove(data);
String[] tempList = new String[(names.size())];
names.toArray(tempList);

for (String token:tempList) {

message = (token + add);
tellEveryone(message);
}
tellEveryone(done);
}

public void tellEveryone(String message) {
// sends message to everyone connected to server
Iterator it = writers.iterator();

while (it.hasNext()) {
try {
PrintWriter writer = (PrintWriter) it.next();
writer.println(message);
System.out.println("Sending" + message);
writer.flush();
} // end try
catch (Exception ex) {
System.out.println("error telling everyone" );
} // end catch
} // end while
} // end tellEveryone()
}
public class Main {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Serveur serv =new Serveur();
serv. setVisible(true);
}

}

4 réponses

KX
Messages postés
16540
Date d'inscription
samedi 31 mai 2008
Statut
Modérateur
Dernière intervention
22 mai 2022
2 957
29 déc. 2012 à 21:22
À la limite, est-ce que le serveur a vraiment besoin d'une interface graphique ?
Le numéro de port est fixé dans le client (5000), et le deuxième paramètre n'est pas utilisé dans ton code (I2), donc la seule chose que tu fais c'est lancer le serveur avec un bouton, et tu ne peux même pas l'arrêter... donc l'interface graphique ne sert vraiment à rien !

Cependant, voici comment tu peux modifier ton code :

@Override
public void actionPerformed(ActionEvent ae)
{
    if(ae.getActionCommand().equals("Ecouter"))
    {
        ecouter.setEnabled(false);
        
        final int I1 = Integer.parseInt(fport.getText()); 
        //final int I2 = Integer.parseInt(fnbMax.getText());
        
        new Thread()
        {
            @Override
            public void run()
            {
                try // Démarrage/Arrêt du serveur
                {
                    serv = new ServerSocket(I1);
                    
                    while(true)
                    {
                        try // Acceptation d'un client
                        {
                            Socket soc = serv.accept();
                            
                            try // Traitement du client
                            {
                                PrintWriter writer = new PrintWriter(soc.getOutputStream());
                                writers.add(writer);
                                ClientHandler w = new ClientHandler(soc,writer);
                                new Thread(w).start();
                            }
                            catch (IOException e)
                            {
                                System.err.println(e);
                            }
                        }
                        catch (IOException e)
                        {
                            System.err.println(e);
                            break;
                        }
                    }
                    
                    serv.close();
                }
                catch (IOException e)
                {
                    ecouter.setEnabled(true);
                    System.err.println(e);
                }
            }
        }.start();
    }
}
1
KX
Messages postés
16540
Date d'inscription
samedi 31 mai 2008
Statut
Modérateur
Dernière intervention
22 mai 2022
2 957
29 déc. 2012 à 22:13
Remarque : il faudrait aussi mettre ecouter.setEnabled(true); juste après serv.close();

                    serv.close();
                    ecouter.setEnabled(true);
                }
                catch (IOException e)
                {
                    ecouter.setEnabled(true);
                    System.err.println(e);
                }
            }
        }.start();
    }
}
0
KX
Messages postés
16540
Date d'inscription
samedi 31 mai 2008
Statut
Modérateur
Dernière intervention
22 mai 2022
2 957
29 déc. 2012 à 19:40
Ce serait bien de dire ce qu'est censé faire ton code...

Perso, en testant, le bouton ne se relâche pas car je reste coincé sur Socket soc=serv.accept() peut-être as-tu une classe Client qu'il serait judicieux de donner pour que je puisse tester ton code. Car pour l'instant, comme je bloque dans l'actionListener le reste de la JFrame est bloqué ce qui explique pourquoi elle ne peux pas se fermer et pourquoi il n'y a pas de repaint (ce qui donne une fenêtre noire lors d'un redimensionnement)

Alors il y aurait beaucoup d'autre chose à redire sur ton code, au niveau de la conception, mais déjà quelques informations complémentaires serait les bienvenues (code client, et but du programme)
0
sillaso
Messages postés
4
Date d'inscription
samedi 29 décembre 2012
Statut
Membre
Dernière intervention
29 décembre 2012

29 déc. 2012 à 20:22
d'abord merci pour votre réponse
bon c'est un programme de chat
et voilà le code client :
import java.net.*;
import java.io.*;
import java.util.*;

public class ChatMain extends javax.swing.JFrame {
String username;
Socket sock;
BufferedReader reader;
PrintWriter writer;
ArrayList<String> userList = new ArrayList();
Boolean isConnected = false;


/** Creates new form Chat */
public ChatMain() {
initComponents();
}

public class IncomingReader implements Runnable{

public void run() {
String stream;
String[] data;
String done = "Done", connect = "Connect", disconnect = "Disconnect", chat = "Chat";

try {
while ((stream = reader.readLine()) != null) {

data = stream.split("¥");

if (data[2].equals(chat)) {

chatTextArea.append(data[0] + ": " + data[1] + "\n");

} else if (data[2].equals(connect)){

chatTextArea.removeAll();
userAdd(data[0]);

} else if (data[2].equals(disconnect)) {


userRemove(data[0]);

} else if (data[2].equals(done)) {


usersList.setText("");
writeUsers();
userList.clear();

}

}
}catch(Exception ex) {
}
}
}

public void ListenThread() {
Thread IncomingReader = new Thread(new ChatMain.IncomingReader());
IncomingReader.start();
}

public void userAdd(String data) {
userList.add(data);

}

public void userRemove(String data) {
chatTextArea.append(data + " has disconnected.\n");

}

public void writeUsers() {
String[] tempList = new String[(userList.size())];
userList.toArray(tempList);
for (String token:tempList) {

usersList.append(token + "\n");

}

}

public void sendDisconnect() {

String bye = (username + "¥ ¥Disconnect");
try{
writer.println(bye); // Sends server the disconnect signal.
writer.flush(); // flushes the buffer
} catch (Exception e) {
chatTextArea.append("Could not send Disconnect message.\n");
}

}

public void Disconnect() {

try {
chatTextArea.append("Disconnected.\n");
sock.close();
} catch(Exception ex) {
chatTextArea.append("Failed to disconnect. \n");
}
isConnected = false;
usernameField.setEditable(true);
usersList.setText("");

}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {

jScrollPane1 = new javax.swing.JScrollPane();
inputTextArea = new javax.swing.JTextArea();
jScrollPane2 = new javax.swing.JScrollPane();
chatTextArea = new javax.swing.JTextArea();
jLabel1 = new javax.swing.JLabel();
usernameField = new javax.swing.JTextField();
connectButton = new javax.swing.JButton();
disconnectButton = new javax.swing.JButton();
sendButton = new javax.swing.JButton();
jScrollPane3 = new javax.swing.JScrollPane();
usersList = new javax.swing.JTextArea();
jLabel2 = new javax.swing.JLabel();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("House Chat");

inputTextArea.setColumns(20);
inputTextArea.setLineWrap(true);
inputTextArea.setRows(5);
jScrollPane1.setViewportView(inputTextArea);

chatTextArea.setColumns(20);
chatTextArea.setEditable(false);
chatTextArea.setFont(new java.awt.Font("Times New Roman", 0, 12)); // NOI18N
chatTextArea.setLineWrap(true);
chatTextArea.setRows(5);
jScrollPane2.setViewportView(chatTextArea);

jLabel1.setText("Username:");

connectButton.setText("Connect");
connectButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
connectButtonActionPerformed(evt);
}
});

disconnectButton.setText("Disconnect");
disconnectButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
disconnectButtonActionPerformed(evt);
}
});

sendButton.setText("Send");
sendButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sendButtonActionPerformed(evt);
}
});

usersList.setColumns(20);
usersList.setEditable(false);
usersList.setRows(5);
jScrollPane3.setViewportView(usersList);

jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel2.setText("Online Users");

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 336, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(sendButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(usernameField, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(connectButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(disconnectButton))
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 419, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane3))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 26, Short.MAX_VALUE)
.addComponent(usernameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(connectButton)
.addComponent(disconnectButton))
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 348, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 261, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(sendButton, javax.swing.GroupLayout.DEFAULT_SIZE, 69, Short.MAX_VALUE))))
.addContainerGap())
);

pack();
}// </editor-fold>//GEN-END:initComponents

private void connectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_connectButtonActionPerformed
// TODO add your handling code here:
if (isConnected == false) {
username = usernameField.getText();
usernameField.setEditable(false);

try {
sock = new Socket("127.0.0.1", 5000);
InputStreamReader streamreader = new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(streamreader);
writer = new PrintWriter(sock.getOutputStream());
writer.println(username + "¥has connected.¥Connect"); // Displays to everyone that user connected.
writer.flush(); // flushes the buffer
isConnected = true; // Used to see if the client is connected.
} catch (Exception ex) {
chatTextArea.append("Cannot Connect! Try Again. \n");
usernameField.setEditable(true);
}
ListenThread();
} else if (isConnected == true) {
chatTextArea.append("You are already connected. \n");
}
}//GEN-LAST:event_connectButtonActionPerformed

private void disconnectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_disconnectButtonActionPerformed
// TODO add your handling code here:
sendDisconnect();
Disconnect();
}//GEN-LAST:event_disconnectButtonActionPerformed

private void sendButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sendButtonActionPerformed
// TODO add your handling code here:
String nothing = "";
if ((inputTextArea.getText()).equals(nothing)) {
inputTextArea.setText("");
inputTextArea.requestFocus();
} else {
try {
writer.println(username + "¥" + inputTextArea.getText() + "¥" + "Chat");
writer.flush(); // flushes the buffer
} catch (Exception ex) {
chatTextArea.append("Message was not sent. \n");
}
inputTextArea.setText("");
inputTextArea.requestFocus();
}

inputTextArea.setText("");
inputTextArea.requestFocus();
}//GEN-LAST:event_sendButtonActionPerformed

/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ChatMain().setVisible(true);
}
});
}

// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextArea chatTextArea;
private javax.swing.JButton connectButton;
private javax.swing.JButton disconnectButton;
private javax.swing.JTextArea inputTextArea;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JButton sendButton;
private javax.swing.JTextField usernameField;
private javax.swing.JTextArea usersList;
// End of variables declaration//GEN-END:variables

}
0
sillaso
Messages postés
4
Date d'inscription
samedi 29 décembre 2012
Statut
Membre
Dernière intervention
29 décembre 2012

29 déc. 2012 à 21:37
c'est pas le code final pour le client!
Merci bien pour votre réponse :)
0