├── Descrição da aplicação.pdf
├── .gitignore
├── src
├── usuario
│ ├── UsuarioEnvia.java
│ ├── UsuarioRecebe.java
│ └── TelaUsuario.java
└── servidor
│ ├── ServidorEnvia.java
│ ├── Servidor.java
│ ├── ServidorRecebe.java
│ └── TelaServidor.java
├── NotaFinal.iml
├── README.md
└── LICENSE
/Descrição da aplicação.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielnunesdc/Chat/HEAD/Descrição da aplicação.pdf
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Compiled class file
2 | *.class
3 |
4 | # Log file
5 | *.log
6 |
7 | # BlueJ files
8 | *.ctxt
9 |
10 | # Mobile Tools for Java (J2ME)
11 | .mtj.tmp/
12 |
13 | # Package Files #
14 | *.jar
15 | *.war
16 | *.ear
17 | *.zip
18 | *.tar.gz
19 | *.rar
20 |
21 | # Directories
22 | *.idea/
23 | *out/
24 |
25 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
26 | hs_err_pid*
27 |
--------------------------------------------------------------------------------
/src/usuario/UsuarioEnvia.java:
--------------------------------------------------------------------------------
1 | package usuario;
2 |
3 | import java.io.IOException;
4 | import java.io.PrintWriter;
5 | import java.net.Socket;
6 |
7 | public class UsuarioEnvia {
8 | UsuarioEnvia(Socket s, Object message, String info, String name) throws IOException {
9 | String messages = info + ",," + message + ",," + name;
10 | PrintWriter pwOut = new PrintWriter(s.getOutputStream(), true);
11 | pwOut.println(messages);
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/NotaFinal.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Chat - Nota Final
2 | Socket Programming - Multi-Client Server chat application using java/Swing.
3 |
4 | My first Java/Swing Chat using Sockets :grin:.
5 |
6 | It's so good you can chat with people! :joy:
7 |
8 | #### *"*Features*"*
9 | - [ ] Make an Icon
10 | - [ ] Detect Links
11 | - [ ] File Transfer
12 | - [ ] Extended Settings
13 | - [ ] Automatic Log for Host
14 | - [ ] Integrate those lit Emojis :100: :ok_hand: :100: :ok_hand:
15 | - [ ] Autoscroll, when new messages fly in
16 |
17 | ...So basically you can just chat with people, nothing more.
18 |
--------------------------------------------------------------------------------
/src/servidor/ServidorEnvia.java:
--------------------------------------------------------------------------------
1 | package servidor;
2 |
3 | import java.io.IOException;
4 | import java.io.PrintWriter;
5 | import java.net.Socket;
6 | import java.util.ArrayList;
7 |
8 | public class ServidorEnvia {
9 | ServidorEnvia(ArrayList listaUsuario, Object message, String info, String name) throws IOException {
10 | String messages = info + "." + message + "." + name;
11 | PrintWriter pwOut = null;
12 | for (Socket s : listaUsuario) { // enviar mensagem para cada cliente necessário
13 | pwOut = new PrintWriter(s.getOutputStream(), true);
14 | pwOut.println(messages);
15 | }
16 | }
17 |
18 | ServidorEnvia(Socket s, Object message, String info) throws IOException {
19 | String messages = info + "." + message;
20 | PrintWriter pwOut = new PrintWriter(s.getOutputStream(), true);
21 | pwOut.println(messages);
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2018 Daniel Nunes
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/src/servidor/Servidor.java:
--------------------------------------------------------------------------------
1 | package servidor;
2 |
3 | import java.io.IOException;
4 | import java.net.ServerSocket;
5 | import java.net.Socket;
6 | import java.util.ArrayList;
7 | import java.util.HashMap;
8 | import java.util.Vector;
9 | import java.util.Map;
10 |
11 | import javax.swing.JOptionPane;
12 |
13 | public class Servidor implements Runnable {
14 | private int porta;
15 | public static ArrayList listaUsuario = null;
16 | public static Vector nomeUsuario = null; // thread security
17 | public static Map map = null;
18 | public static ServerSocket ss = null;
19 | public static boolean flag = true;
20 |
21 | public Servidor(int porta) throws IOException {
22 | this.porta = porta;
23 | }
24 |
25 | public void run() {
26 | Socket s = null;
27 | listaUsuario = new ArrayList(); //Contém portaas dos usuários
28 | nomeUsuario = new Vector(); //contém usuários
29 | map = new HashMap(); //name to socket one on one map
30 |
31 | System.out.println("Servidor iniciado!");
32 |
33 | try {
34 | ss = new ServerSocket(porta);
35 | } catch (IOException e1) {
36 | e1.printStackTrace();
37 | }
38 |
39 | while (flag) {
40 | try {
41 | s = ss.accept();
42 | listaUsuario.add(s);
43 | new Thread(new ServidorRecebe(s, listaUsuario, nomeUsuario, map)).start();
44 | } catch (IOException e) {
45 | JOptionPane.showMessageDialog(TelaServidor.window, "Servidor encerrado!");
46 | }
47 | }
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/usuario/UsuarioRecebe.java:
--------------------------------------------------------------------------------
1 | package usuario;
2 |
3 | import javax.swing.*;
4 | import java.io.BufferedReader;
5 | import java.io.IOException;
6 | import java.io.InputStreamReader;
7 | import java.net.Socket;
8 |
9 | public class UsuarioRecebe implements Runnable {
10 | private Socket s;
11 |
12 | public UsuarioRecebe(Socket s) {
13 | this.s = s;
14 | }
15 |
16 | public void run() {
17 | try {
18 | BufferedReader brIn = new BufferedReader(new InputStreamReader(s.getInputStream()));
19 | while (true) {
20 | String s = brIn.readLine();
21 | String[] strs = s.split("\\.");
22 | String info = strs[0];
23 | String name = "", line = "";
24 | if (strs.length == 2)
25 | line = strs[1];
26 | else if (strs.length == 3) {
27 | line = strs[1];
28 | name = strs[2];
29 | }
30 |
31 | if (info.equals("1")) { // 1 para msg
32 | TelaUsuario.textMessage.append(line + "\r\n");
33 | TelaUsuario.textMessage.setCaretPosition(TelaUsuario.textMessage.getText().length());
34 | } else if (info.equals("2") || info.equals("3")) { // 2 para entrar e 3 para sair
35 | if (info.equals("2")) {
36 | TelaUsuario.textMessage.append("(Alerta) " + name + " entrou!" + "\r\n");
37 | TelaUsuario.textMessage.setCaretPosition(TelaUsuario.textMessage.getText().length());
38 | } else {
39 | TelaUsuario.textMessage.append("(Alerta) " + name + " saiu!" + "\r\n");
40 | TelaUsuario.textMessage.setCaretPosition(TelaUsuario.textMessage.getText().length());
41 | }
42 | String list = line.substring(1, line.length() - 1);
43 | String[] data = list.split(",");
44 | TelaUsuario.user.clearSelection();
45 | TelaUsuario.user.setListData(data);
46 | } else if (info.equals("4")) { // 4 para alertas
47 | TelaUsuario.connect.setText("entrar");
48 | TelaUsuario.sair.setText("sair");
49 | TelaUsuario.socket.close();
50 | TelaUsuario.socket = null;
51 | JOptionPane.showMessageDialog(TelaUsuario.window, "Alguém já está usando esse nome de usuário");
52 | break;
53 | } else if (info.equals("5")) { // 5 para fechar o servidor
54 | TelaUsuario.connect.setText("entrou");
55 | TelaUsuario.sair.setText("saiu");
56 | TelaUsuario.socket.close();
57 | TelaUsuario.socket = null;
58 | break;
59 | } else if (info.equals("6")) { // 6 para msg privada
60 | TelaUsuario.textMessage.append("(Mensagem privada) " + line + "\r\n");
61 | TelaUsuario.textMessage.setCaretPosition(TelaUsuario.textMessage.getText().length());
62 | } else if (info.equals("7")) {
63 | JOptionPane.showMessageDialog(TelaUsuario.window, "Esse usuário não está online");
64 | }
65 | }
66 | } catch (IOException e) {
67 | JOptionPane.showMessageDialog(TelaUsuario.window, "O usuário saiu");
68 | }
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/src/servidor/ServidorRecebe.java:
--------------------------------------------------------------------------------
1 | package servidor;
2 |
3 | import java.io.BufferedReader;
4 | import java.io.IOException;
5 | import java.io.InputStreamReader;
6 | import java.net.Socket;
7 | import java.util.ArrayList;
8 | import java.util.Map;
9 | import java.util.Vector;
10 |
11 | public class ServidorRecebe implements Runnable {
12 | private Socket socket;
13 | private ArrayList listaUsuario;
14 | private Vector nomeUsuario;
15 | private Map map;
16 |
17 |
18 | public ServidorRecebe(Socket s, ArrayList listaUsuario, Vector nomeUsuario, Map map) {
19 | this.socket = s;
20 | this.listaUsuario = listaUsuario;
21 | this.nomeUsuario = nomeUsuario;
22 | this.map = map;
23 | }
24 |
25 | public void run() {
26 | try {
27 | BufferedReader brIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
28 | while (true) {
29 | String s = brIn.readLine();
30 | String[] strs = s.split(",,");
31 | String info = strs[0]; //judge the kind of info
32 | String line = strs[1];
33 | //System.out.println(line);
34 | String name = "";
35 | if (strs.length == 3)
36 | name = strs[2];
37 |
38 | if (info.equals("1")) { // 1 para Nova requisição de mensagem
39 | TelaServidor.console.append("Nova mensagem ---->> " + line + "\r\n");
40 | TelaServidor.console.setCaretPosition(TelaServidor.console.getText().length());
41 | new ServidorEnvia(listaUsuario, line, "1", "");
42 | } else if (info.equals("2")) { // 2 para login
43 | if (!nomeUsuario.contains(line)) {
44 | TelaServidor.console.append("Novo login requisitado ---->> " + line + "\r\n");
45 | TelaServidor.console.setCaretPosition(TelaServidor.console.getText().length());
46 | nomeUsuario.add(line);
47 | map.put(line, socket);
48 | TelaServidor.user.setListData(nomeUsuario);
49 | new ServidorEnvia(listaUsuario, nomeUsuario, "2", line);
50 | } else {
51 | TelaServidor.console.append("Login duplicado ---->> " + line + "\r\n");
52 | TelaServidor.console.setCaretPosition(TelaServidor.console.getText().length());
53 | listaUsuario.remove(socket);
54 | new ServidorEnvia(socket, "", "4");
55 | }
56 | } else if (info.equals("3")) { // 3 para sair
57 | TelaServidor.console.append("Saiu ---->> " + line + "\r\n");
58 | TelaServidor.console.setCaretPosition(TelaServidor.console.getText().length());
59 | nomeUsuario.remove(line);
60 | listaUsuario.remove(socket);
61 | map.remove(line);
62 | TelaServidor.user.setListData(nomeUsuario);
63 | new ServidorEnvia(listaUsuario, nomeUsuario, "3", line);
64 | socket.close();
65 | break; // quebra de info
66 | } else if (info.equals("4")) { // 4 para msg privada
67 | TelaServidor.console.append("Nova mensagem privada ---->> " + line + "\r\n");
68 | TelaServidor.console.setCaretPosition(TelaServidor.console.getText().length());
69 | if (map.containsKey(name))
70 | new ServidorEnvia(map.get(name), line, "6");
71 | else
72 | new ServidorEnvia(socket, "", "7");
73 | }
74 | }
75 | } catch (IOException e) {
76 | e.printStackTrace();
77 | }
78 | }
79 |
80 | }
81 |
--------------------------------------------------------------------------------
/src/servidor/TelaServidor.java:
--------------------------------------------------------------------------------
1 | package servidor;
2 |
3 | import javax.swing.JButton;
4 | import javax.swing.JFrame;
5 | import javax.swing.JLabel;
6 | import javax.swing.JList;
7 | import javax.swing.JOptionPane;
8 | import javax.swing.JScrollPane;
9 | import javax.swing.JTextArea;
10 | import javax.swing.JTextField;
11 |
12 | import java.awt.event.ActionEvent;
13 | import java.awt.event.ActionListener;
14 | import java.awt.event.KeyAdapter;
15 | import java.awt.event.KeyEvent;
16 | import java.awt.event.WindowAdapter;
17 | import java.awt.event.WindowEvent;
18 | import java.io.IOException;
19 |
20 | public class TelaServidor {
21 | public static JFrame window;
22 | public static int ports;
23 | public static JTextArea console;
24 | public static JList user;
25 |
26 | JButton inicia, sair, enviar;
27 | JTextField nomeServidor, portaServidor, message;
28 |
29 | //main
30 | public static void main(String[] args) {
31 | new TelaServidor();
32 | }
33 |
34 | public TelaServidor() {
35 | init();
36 | }
37 |
38 | public void init() { // layout do servidor
39 | window = new JFrame("Servidor | Nota Final");
40 | window.setLayout(null);
41 | window.setBounds(200, 200, 500, 350);
42 | window.setResizable(false);
43 |
44 | JLabel labelnomeServidor = new JLabel("Servidor:");
45 | labelnomeServidor.setBounds(10, 8, 80, 30);
46 | window.add(labelnomeServidor);
47 |
48 | nomeServidor = new JTextField();
49 | nomeServidor.setBounds(80, 8, 60, 30);
50 | window.add(nomeServidor);
51 |
52 | JLabel label_porta = new JLabel("Porta:");
53 | label_porta.setBounds(150, 8, 60, 30);
54 | window.add(label_porta);
55 |
56 | portaServidor = new JTextField();
57 | portaServidor.setBounds(200, 8, 70, 30);
58 | window.add(portaServidor);
59 |
60 | inicia = new JButton("Iniciar");
61 | inicia.setBounds(280, 8, 90, 30);
62 | window.add(inicia);
63 |
64 | sair = new JButton("Sair");
65 | sair.setBounds(380, 8, 110, 30);
66 | window.add(sair);
67 |
68 | console = new JTextArea();
69 | console.setBounds(10, 70, 340, 320);
70 | console.setEditable(false); // não pode ser editado
71 |
72 | console.setLineWrap(true); // automatic content line feed
73 | console.setWrapStyleWord(true);
74 |
75 | JLabel label_text = new JLabel("Painel do Servidor");
76 | label_text.setBounds(100, 47, 190, 30);
77 | window.add(label_text);
78 |
79 | JScrollPane paneText = new JScrollPane(console);
80 | paneText.setBounds(10, 70, 340, 220);
81 | window.add(paneText);
82 |
83 | JLabel label_listaUsuario = new JLabel("Lista de Usuários");
84 | label_listaUsuario.setBounds(357, 47, 180, 30);
85 | window.add(label_listaUsuario);
86 |
87 | user = new JList();
88 | JScrollPane paneUser = new JScrollPane(user);
89 | paneUser.setBounds(355, 70, 130, 220);
90 | window.add(paneUser);
91 |
92 | message = new JTextField();
93 | message.setBounds(0, 0, 0, 0);
94 | window.add(message);
95 |
96 | enviar = new JButton("Enviar");
97 | enviar.setBounds(0, 0, 0, 0);
98 | window.add(enviar);
99 |
100 | myEvent(); // add listeners
101 | window.setVisible(true);
102 | }
103 |
104 | public void myEvent() {
105 | window.addWindowListener(new WindowAdapter() {
106 | public void windowClosing(WindowEvent e) {
107 | if (Servidor.listaUsuario != null && Servidor.listaUsuario.size() != 0) {
108 | try {
109 | new ServidorEnvia(Servidor.listaUsuario, "", "5", "");
110 | } catch (IOException e1) {
111 | e1.printStackTrace();
112 | }
113 | }
114 | System.exit(0); // sair da janela
115 | }
116 | });
117 |
118 | sair.addActionListener(new ActionListener() {
119 | public void actionPerformed(ActionEvent e) {
120 | if (Servidor.ss == null || Servidor.ss.isClosed()) {
121 | JOptionPane.showMessageDialog(window, "O Servidor foi fechado!");
122 | } else {
123 | if (Servidor.listaUsuario != null && Servidor.listaUsuario.size() != 0) {
124 | try {
125 | new ServidorEnvia(Servidor.listaUsuario, "", "5", "");
126 | } catch (IOException e1) {
127 | e1.printStackTrace();
128 | }
129 | }
130 | try {
131 | inicia.setText("Iniciar");
132 | sair.setText("Fechar");
133 | Servidor.ss.close();
134 | Servidor.ss = null;
135 | Servidor.listaUsuario = null;
136 | Servidor.flag = false; // importante
137 | } catch (IOException e1) {
138 | e1.printStackTrace();
139 | }
140 | }
141 | }
142 | });
143 |
144 | inicia.addActionListener(new ActionListener() {
145 | public void actionPerformed(ActionEvent e) {
146 | if (Servidor.ss != null && !Servidor.ss.isClosed()) {
147 | JOptionPane.showMessageDialog(window, "O servidor foi iniciado!");
148 | } else {
149 | ports = getPorta();
150 | if (ports != 0) {
151 | try {
152 | Servidor.flag = true;
153 | new Thread(new Servidor(ports)).start(); // inicia servidor thread
154 | inicia.setText("Iniciado");
155 | sair.setText("Fechar");
156 | } catch (IOException e1) {
157 | JOptionPane.showMessageDialog(window, "Falha ao rodar");
158 | }
159 | }
160 | }
161 | }
162 | });
163 |
164 | message.addKeyListener(new KeyAdapter() {
165 | public void keyPressed(KeyEvent e) {
166 | if (e.getKeyCode() == KeyEvent.VK_ENTER) {
167 | enviarMsg();
168 | }
169 | }
170 | });
171 |
172 | enviar.addActionListener(new ActionListener() {
173 | public void actionPerformed(ActionEvent e) {
174 | enviarMsg();
175 | }
176 | });
177 | }
178 |
179 | public void enviarMsg() {
180 | String messages = message.getText();
181 | if ("".equals(messages)) {
182 | JOptionPane.showMessageDialog(window, "Não há nada para enviar!");
183 | } else if (Servidor.listaUsuario == null || Servidor.listaUsuario.size() == 0) {
184 | JOptionPane.showMessageDialog(window, "Não há conexão!");
185 | } else {
186 | try {
187 | new ServidorEnvia(Servidor.listaUsuario, getnomeServidor() + ": " + messages, "1", "");
188 | message.setText(null);
189 | } catch (IOException e1) {
190 | JOptionPane.showMessageDialog(window, "Falha ao enviar!");
191 | }
192 | }
193 | }
194 |
195 | public int getPorta() {
196 | String porta = portaServidor.getText();
197 | String name = nomeServidor.getText();
198 | if ("".equals(porta) || "".equals(name)) {
199 | JOptionPane.showMessageDialog(window, "Nenhuma porta ou Nome de usuário encontrada!");
200 | return 0;
201 | } else {
202 | return Integer.parseInt(porta);
203 | }
204 | }
205 |
206 | public String getnomeServidor() {
207 | return nomeServidor.getText();
208 | }
209 | }
--------------------------------------------------------------------------------
/src/usuario/TelaUsuario.java:
--------------------------------------------------------------------------------
1 | package usuario;
2 |
3 | import java.awt.event.ActionEvent;
4 | import java.awt.event.ActionListener;
5 | import java.awt.event.WindowAdapter;
6 | import java.awt.event.WindowEvent;
7 | import java.io.IOException;
8 | import java.net.Socket;
9 | import javax.swing.JButton;
10 | import javax.swing.JFrame;
11 | import javax.swing.JLabel;
12 | import javax.swing.JList;
13 | import javax.swing.JOptionPane;
14 | import javax.swing.JScrollPane;
15 | import javax.swing.JTextArea;
16 | import javax.swing.JTextField;
17 |
18 | public class TelaUsuario {
19 | public static JFrame window;
20 | public static JButton connect, sair;
21 | public static JTextArea textMessage;
22 | public static Socket socket = null;
23 | public static JList user;
24 |
25 | JTextField nomeUsuario, porta, message, msgPriv;
26 | JButton msgPrivada, enviar;
27 |
28 | //main
29 | public static void main(String[] args) {
30 | new TelaUsuario();
31 | }
32 |
33 | public TelaUsuario() {
34 | init();
35 | }
36 |
37 | public void init() {
38 | window = new JFrame("Bate Papo | Nota Final");
39 | window.setLayout(null);
40 | window.setBounds(400, 400, 530, 420);
41 | window.setResizable(true);
42 |
43 | JLabel label_nomeUsuario = new JLabel("Usuário:");
44 | label_nomeUsuario.setBounds(10, 28, 70, 30);
45 | window.add(label_nomeUsuario);
46 |
47 | nomeUsuario = new JTextField();
48 | nomeUsuario.setBounds(80, 28, 70, 30);
49 | window.add(nomeUsuario);
50 |
51 | JLabel label_porta = new JLabel("porta:");
52 | label_porta.setBounds(180, 28, 50, 30);
53 | window.add(label_porta);
54 |
55 | porta = new JTextField();
56 | porta.setBounds(230, 28, 50, 30);
57 | window.add(porta);
58 |
59 | connect = new JButton("Entrar");
60 | connect.setBounds(300, 28, 90, 30);
61 | window.add(connect);
62 |
63 | sair = new JButton("Sair");
64 | sair.setBounds(400, 28, 90, 30);
65 | window.add(sair);
66 |
67 | textMessage = new JTextArea();
68 | textMessage.setBounds(10, 70, 340, 220);
69 | textMessage.setEditable(false);
70 |
71 | textMessage.setLineWrap(true);
72 | textMessage.setWrapStyleWord(true);
73 |
74 | JLabel label_text = new JLabel("Área de Mensagens");
75 | label_text.setBounds(100, 58, 200, 50);
76 | window.add(label_text);
77 |
78 | JScrollPane paneText = new JScrollPane(textMessage);
79 | paneText.setBounds(10, 90, 360, 240);
80 | window.add(paneText);
81 |
82 | JLabel label_listaUsuario = new JLabel("Lista de Usuários");
83 | label_listaUsuario.setBounds(380, 58, 200, 50);
84 | window.add(label_listaUsuario);
85 |
86 | user = new JList();
87 | JScrollPane paneUser = new JScrollPane(user);
88 | paneUser.setBounds(375, 90, 140, 240);
89 | window.add(paneUser);
90 |
91 | JLabel label_Alerta = new JLabel("Digite Mgs para o grupo");
92 | label_Alerta.setBounds(10, 320, 180, 50);
93 | window.add(label_Alerta);
94 |
95 | message = new JTextField();
96 | message.setBounds(10, 355, 188, 30);
97 | message.setText(null);
98 | window.add(message);
99 |
100 | JLabel label_Aviso = new JLabel("Add usuário para msg privada");
101 | label_Aviso.setBounds(272, 320, 250, 50);
102 | window.add(label_Aviso);
103 |
104 | msgPriv = new JTextField();
105 | msgPriv.setBounds(272, 355, 100, 30);
106 | window.add(msgPriv);
107 |
108 | msgPrivada = new JButton("Msg Privada");
109 | msgPrivada.setBounds(376, 355, 140, 30);
110 | window.add(msgPrivada);
111 |
112 | enviar = new JButton("Grupo");
113 | enviar.setBounds(190, 355, 77, 30);
114 | window.add(enviar);
115 |
116 | myEvent(); // add conectados/ouvindo a porta
117 | window.setVisible(true);
118 | }
119 |
120 | public void myEvent() {
121 | window.addWindowListener(new WindowAdapter() {
122 | public void windowClosing(WindowEvent e) {
123 | if (socket != null && socket.isConnected()) {
124 | try {
125 | new UsuarioEnvia(socket, getnomeUsuario(), "3", "");
126 | } catch (IOException e1) {
127 | e1.printStackTrace();
128 | }
129 | }
130 | System.exit(0);
131 | }
132 | });
133 |
134 | sair.addActionListener(new ActionListener() {
135 | public void actionPerformed(ActionEvent e) {
136 | if (socket == null) {
137 | JOptionPane.showMessageDialog(window, "A conexão foi encerrada!");
138 | } else if (socket != null && socket.isConnected()) {
139 | try {
140 | new UsuarioEnvia(socket, getnomeUsuario(), "3", "");
141 | connect.setText("Entrar");
142 | sair.setText("saiu!");
143 | socket.close();
144 | socket = null;
145 | } catch (IOException e1) {
146 | e1.printStackTrace();
147 | }
148 | }
149 | }
150 | });
151 |
152 | connect.addActionListener(new ActionListener() {
153 | public void actionPerformed(ActionEvent e) {
154 | if (socket != null && socket.isConnected()) {
155 | JOptionPane.showMessageDialog(window, "Conectado!");
156 | } else {
157 | String ipString = "127.0.0.1";
158 | String portaClinet = porta.getText();
159 | String name = nomeUsuario.getText();
160 |
161 | if ("".equals(name) || "".equals(portaClinet)) {
162 | JOptionPane.showMessageDialog(window, "O usuário ou a portaa não podem estar vazios!");
163 | } else {
164 | try {
165 | int portas = Integer.parseInt(portaClinet);
166 | socket = new Socket(ipString, portas);
167 | connect.setText("Entrou");
168 | sair.setText("sair");
169 | new UsuarioEnvia(socket, getnomeUsuario(), "2", "");
170 | new Thread(new UsuarioRecebe(socket)).start();
171 | } catch (Exception e2) {
172 | JOptionPane.showMessageDialog(window, "falha em conectar-se, verifique o ip e a portaa");
173 | }
174 | }
175 | }
176 | }
177 | });
178 |
179 | msgPrivada.addActionListener(new ActionListener() {
180 | public void actionPerformed(ActionEvent e) {
181 | enviarMsgmsgPriv();
182 | }
183 | });
184 |
185 | enviar.addActionListener(new ActionListener() {
186 | public void actionPerformed(ActionEvent e) {
187 | enviarMsg();
188 | }
189 | });
190 | }
191 |
192 | public void enviarMsg() {
193 | String messages = message.getText();
194 | if ("".equals(messages)) {
195 | JOptionPane.showMessageDialog(window, "Não há nada para enviar");
196 | } else if (socket == null || !socket.isConnected()) {
197 | JOptionPane.showMessageDialog(window, "Sem conexão");
198 | } else {
199 | try {
200 | new UsuarioEnvia(socket, getnomeUsuario() + ": " + messages, "1", "");
201 | message.setText(null);
202 | } catch (IOException e1) {
203 | JOptionPane.showMessageDialog(window, "falha ao enviar!");
204 | }
205 | }
206 | }
207 |
208 | public void enviarMsgmsgPriv() {
209 | String messages = message.getText();
210 | if ("".equals(messages)) {
211 | JOptionPane.showMessageDialog(window, "Não há nada para enviar!");
212 | } else if (socket == null || !socket.isConnected()) {
213 | JOptionPane.showMessageDialog(window, "Sem conexão");
214 | } else {
215 | try {
216 | new UsuarioEnvia(socket, getnomeUsuario() + ": " + messages, "4", getmsgPrivada());
217 | TelaUsuario.textMessage.append(getnomeUsuario() + ": " + messages + "\r\n");
218 | message.setText(null);
219 | } catch (IOException e1) {
220 | JOptionPane.showMessageDialog(window, "Mensagem privada não enviado!");
221 | }
222 | }
223 | }
224 |
225 | public String getnomeUsuario() {
226 | return nomeUsuario.getText();
227 | }
228 |
229 | public String getmsgPrivada() {
230 | return msgPriv.getText();
231 | }
232 | }
233 |
--------------------------------------------------------------------------------