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
| import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import server.TextDemo;
public class Client extends JPanel implements ActionListener {
protected static final int PORT=4550;
protected String nomclient="Matthieu";
protected static final String IP="127.0.0.1";
protected JTextField textField;
protected JTextArea textArea;
private final static String newline = "\n";
public Client() {
super(new GridBagLayout());
textField = new JTextField(20);
textField.addActionListener(this);
textArea = new JTextArea(5, 20);
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
//Add Components to this panel.
GridBagConstraints c = new GridBagConstraints();
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.HORIZONTAL;
add(textField, c);
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
c.weighty = 1.0;
add(scrollPane, c);
}
public static void main(String[] args){
Socket s=null;
try{
DataInputStream dis;
s=new Socket(IP,PORT);
InputStreamReader isr=new InputStreamReader(s.getInputStream());//octet transformé du socket s en char
BufferedReader canalLecture=newBufferedReader(isr);//buffer les char arrivant dans le canalLecture
BufferedReader console=new BufferedReader(new InputStreamReader(System.in));//buff les char arrivant
PrintStream canalEcriture=new PrintStream(s.getOutputStream());//
System.out.println("Connection établie:"+s.getInetAddress()+"port:"+s.getPort());
String ligne;
while(true){
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
ligne=console.readLine();
if((ligne !=null)||(!ligne.equals(""))){
canalEcriture.println(ligne);
}
System.out.println(canalLecture.readLine());
}
}catch(Exception e){e.printStackTrace();}
}
public void actionPerformed(ActionEvent evt) {
String text = textField.getText();
textArea.append(text+ newline);
textField.selectAll();
//Make sure the new text is visible, even if there
//was a selection in the text area.
textArea.setCaretPosition(textArea.getDocument().getLength());
}
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Client");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Add contents to the window.
frame.add(new Client());
//Display the window.
frame.pack();
frame.setVisible(true);
}
} |
Partager