Cliente.java
1
2
3
4
5
6
7
8
9
10 import java.awt.BorderLayout;
11 import java.awt.FlowLayout;
12 import java.awt.event.ActionEvent;
13 import java.awt.event.ActionListener;
14 import java.io.BufferedReader;
15 import java.io.IOException;
16 import java.io.InputStreamReader;
17 import java.io.PrintStream;
18 import java.net.Socket;
19
20 import javax.swing.JButton;
21 import javax.swing.JFrame;
22 import javax.swing.JPanel;
23 import javax.swing.JTextArea;
24 import javax.swing.JTextField;
25
26 class AccionEnviar implements ActionListener{
27 private JTextField areaTexto;
28 private PrintStream salida;
29 private String login;
30
31 public AccionEnviar(Socket s, JTextField at, String l){
32 areaTexto = at;
33 try {
34 salida = new PrintStream(s.getOutputStream());
35 } catch (IOException e) {
36 e.printStackTrace();
37 }
38 login = l;
39 }
40
41 public void actionPerformed(ActionEvent e){
42 salida.println(login + "> " + areaTexto.getText() );
43 areaTexto.setText("");
44 }
45 }
46
47 class Talk {
48 private Socket socket;
49 private String login;
50
51 public Talk(Socket s, String l){
52 socket = s;
53 login = l;
54 }
55
56 public void hablar(){
57 JFrame marco = new JFrame(login);
58 marco.setLayout(new BorderLayout());
59 JTextArea areaTexto = new JTextArea("");
60 areaTexto.setEditable(false);
61 marco.add(areaTexto, "Center");
62 JPanel panel = new JPanel(new FlowLayout());
63 marco.add(panel, "South");
64 JTextField campoTexto = new JTextField(30);
65 panel.add(campoTexto);
66 JButton botonEnviar = new JButton("Enviar");
67 AccionEnviar ae = new AccionEnviar(socket, campoTexto, login);
68 botonEnviar.addActionListener(ae);
69 panel.add(botonEnviar);
70 marco.setSize(600,800);
71 marco.setVisible(true);
72
73 BufferedReader entrada;
74 PrintStream salida;
75 try {
76 salida = new PrintStream(socket.getOutputStream());
77 salida.println(login + " se he conectado" );
78
79 entrada = new BufferedReader(new InputStreamReader(socket.getInputStream()));
80 String mensaje;
81 while( (mensaje = entrada.readLine()) != null){
82 areaTexto.setText(areaTexto.getText() + mensaje + "\n");
83 }
84 } catch (IOException e) {
85 e.printStackTrace();
86 }
87 }
88 }
89
90 public class Cliente {
91 public static void main(String[] args)throws IOException {
92 String direccion = "localhost";
93 int puerto = 9999;
94 String login = "Nadie";
95
96 if(args.length >= 1){
97 login = args[0];
98 }
99 if(args.length >= 2){
100 direccion = args[1];
101 }
102 if(args.length >= 3){
103 puerto = Integer.parseInt(args[2]);
104 }
105 Socket socket = new Socket(direccion, puerto);
106
107 Talk talk = new Talk(socket, login);
108 talk.hablar();
109
110 socket.close();
111 System.exit(0);
112 }
113
114 }
CategoryJava | CategoryProgramacion