Olá, me chamo Carlos,
Fiz este chat Multi usuários baseado em tutoriais na internet, mas agora estou tentando implementar nele a transferência de arquivos, mas nada que eu tento dá certo, sei que é algo um pouco amplo demais pra perguntar, e desculpa a quantidade de códigos no post não sei se pode postar o programa inteiro assim, mas se alguém puder me ajudar a colocar essa transferência de arquivos eu agradeço.
Aplicação Cliente :
Classe Cliente:
package com.tiete.app;
import com.tiete.app.frame.ClienteFrame;
/**
*
* @author Carlos Santana
*/
public class Cliente {
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ClienteFrame().setVisible(true);
}
});
}
}
Classe ChatMessage:
package com.tiete.app.bean;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
/**
*
* @author Carlos Santana
*/
public class ChatMessage implements Serializable {
private String name;
private String text;
private String nameReserved;
private Set<String> setOnlines;
private Action action;
public ChatMessage() {
this.setOnlines = new HashSet<>();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getNameReserved() {
return nameReserved;
}
public void setNameReserved(String nameReserved) {
this.nameReserved = nameReserved;
}
public Set<String> getSetOnlines() {
return setOnlines;
}
public void setSetOnlines(Set<String> setOnlines) {
this.setOnlines = setOnlines;
}
public Action getAction() {
return action;
}
public void setAction(Action action) {
this.action = action;
}
public enum Action {
CONNECT, DISCONNECT, SEND_ONE, SEND_ALL, USERS_ONLINE
}
}
Classe ClienteFrame:
package com.tiete.app.frame;
import com.tiete.app.bean.ChatMessage;
import com.tiete.app.bean.ChatMessage.Action;
import com.tiete.app.bean.FileMessage;
import com.tiete.app.service.ClienteService;
import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
/**
*
* @author Carlos Santana
*/
public class ClienteFrame extends javax.swing.JFrame {
private Socket socket;
private ChatMessage message;
private ClienteService service;
private ObjectOutputStream output;
/**
* Creates new form ClienteFrame
*/
public ClienteFrame() {
initComponents();
}
private class ListenerSocket implements Runnable {
private ObjectInputStream input;
public ListenerSocket(Socket socket) {
try {
this.input = new ObjectInputStream(socket.getInputStream());
} catch (IOException ex) {
Logger.getLogger(ClienteFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
public void run() {
ChatMessage message = null;
try {
while ((message = (ChatMessage) input.readObject()) != null) {
Action action = message.getAction();
switch (action) {
case CONNECT:
connected(message);
break;
case DISCONNECT:
disconnected(); //Chama Metodo de Desconexão
socket.close(); //Fecha o Socket
break;
case SEND_ONE:
System.out.println("::: " + message.getText() + " :::");
receive(message);
break;
case USERS_ONLINE:
refreshOnlines(message);
break;
default:
break;
}
}
} catch (IOException | ClassNotFoundException ex) {
Logger.getLogger(ClienteFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private void connected(ChatMessage message) {
if (message.getText().equals("Rejeitado")) {
this.txtName.setText("");
JOptionPane.showMessageDialog(this, "Conexão não realizada!\nTente novamente com um novo usuário.");
return;
}
this.message = message;
this.btnConnectar.setEnabled(false);
this.txtName.setEditable(false);
this.btnSair.setEnabled(true);
this.txtAreaSend.setEnabled(true);
this.txtAreaReceive.setEnabled(true);
this.btnEnviar.setEnabled(true);
this.btnLimpar.setEnabled(true);
this.btnFile.setEnabled(true);
JOptionPane.showMessageDialog(this, "Conectado com sucesso !");
}
private void disconnected() {
this.btnConnectar.setEnabled(true);
this.txtName.setEditable(true);
this.btnSair.setEnabled(false);
this.txtAreaSend.setEnabled(false);
this.txtAreaReceive.setEnabled(false);
this.btnEnviar.setEnabled(false);
this.btnLimpar.setEnabled(false);
this.btnFile.setEnabled(false);
this.txtAreaReceive.setText("");
this.txtAreaSend.setText("");
JOptionPane.showMessageDialog(this, "Desconectado com sucesso !");
}
private void receive(ChatMessage message) {
this.txtAreaReceive.append(message.getName() + " diz: \n" + message.getText() + "\n");
}
private void refreshOnlines(ChatMessage message) {
System.out.println(message.getSetOnlines().toString());
Set<String> names = message.getSetOnlines();
names.remove(message.getName());
String[] array = (String[]) names.toArray(new String[names.size()]);
this.listOnlines.setListData(array);
this.listOnlines.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
this.listOnlines.setLayoutOrientation(JList.VERTICAL);
}
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
txtName = new javax.swing.JTextField();
btnConnectar = new javax.swing.JButton();
btnSair = new javax.swing.JButton();
jPanel2 = new javax.swing.JPanel();
jScrollPane3 = new javax.swing.JScrollPane();
listOnlines = new javax.swing.JList();
jPanel3 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
txtAreaReceive = new javax.swing.JTextArea();
jScrollPane2 = new javax.swing.JScrollPane();
txtAreaSend = new javax.swing.JTextArea();
btnEnviar = new javax.swing.JButton();
btnLimpar = new javax.swing.JButton();
btnFile = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Tietê Com v 2.5");
setBackground(new java.awt.Color(0, 204, 204));
setResizable(false);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Conectar"));
btnConnectar.setText("Conectar");
btnConnectar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnConnectarActionPerformed(evt);
}
});
btnSair.setText("Sair");
btnSair.setEnabled(false);
btnSair.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSairActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(txtName)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnConnectar)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnSair)
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnConnectar)
.addComponent(btnSair))
);
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Online"));
jScrollPane3.setViewportView(listOnlines);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 128, Short.MAX_VALUE)
.addContainerGap())
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane3)
);
jPanel3.setBorder(javax.swing.BorderFactory.createEtchedBorder());
txtAreaReceive.setEditable(false);
txtAreaReceive.setColumns(20);
txtAreaReceive.setRows(5);
txtAreaReceive.setEnabled(false);
jScrollPane1.setViewportView(txtAreaReceive);
txtAreaSend.setColumns(20);
txtAreaSend.setRows(5);
txtAreaSend.setEnabled(false);
jScrollPane2.setViewportView(txtAreaSend);
btnEnviar.setText("Enviar");
btnEnviar.setEnabled(false);
btnEnviar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnEnviarActionPerformed(evt);
}
});
btnLimpar.setText("Limpar");
btnLimpar.setEnabled(false);
btnLimpar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLimparActionPerformed(evt);
}
});
btnFile.setText("Enviar Arquivo");
btnFile.setEnabled(false);
btnFile.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnFileActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 639, Short.MAX_VALUE)
.addComponent(jScrollPane2)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addComponent(btnFile)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnLimpar)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnEnviar)))
.addContainerGap())
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 407, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnEnviar)
.addComponent(btnLimpar)
.addComponent(btnFile))
.addContainerGap())
);
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)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 185, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
pack();
}// </editor-fold>
private void btnConnectarActionPerformed(java.awt.event.ActionEvent evt) {
String name = this.txtName.getText();
if (!name.isEmpty()) {
this.message = new ChatMessage();
this.message.setAction(Action.CONNECT);
this.message.setName(name);
this.service = new ClienteService();
this.socket = this.service.connect();
new Thread(new ListenerSocket(this.socket)).start();
this.service.send(message);
}
}
private void btnSairActionPerformed(java.awt.event.ActionEvent evt) {
ChatMessage message = new ChatMessage();
message.setName(this.message.getName());
message.setAction(Action.DISCONNECT);
this.service.send(message);
disconnected();
}
private void btnLimparActionPerformed(java.awt.event.ActionEvent evt) {
this.txtAreaSend.setText("");
}
private void btnEnviarActionPerformed(java.awt.event.ActionEvent evt) {
String text = this.txtAreaSend.getText();
String name = this.message.getName();
this.message = new ChatMessage();
if (this.listOnlines.getSelectedIndex() > -1) {
this.message.setNameReserved((String) this.listOnlines.getSelectedValue());
this.message.setAction(Action.SEND_ONE);
this.listOnlines.clearSelection();
} else {
this.message.setAction(Action.SEND_ALL);
}
if (!text.isEmpty()) {
this.message.setName(name);
this.message.setText(text);
this.txtAreaReceive.append("Você disse: \n" + text + "\n");
this.service.send(this.message);
}
this.txtAreaSend.setText("");
}
private void btnFileActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser ch = new JFileChooser();
String nome = message.getName();
int op = ch.showOpenDialog(null);
if(op == JFileChooser.APPROVE_OPTION){
try {
File file = ch.getSelectedFile();
this.output = new ObjectOutputStream(socket.getOutputStream());
this.output.writeObject(new FileMessage(nome, file));
} catch (IOException ex) {
Logger.getLogger(ClienteFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
// Variables declaration - do not modify
private javax.swing.JButton btnConnectar;
private javax.swing.JButton btnEnviar;
private javax.swing.JButton btnFile;
private javax.swing.JButton btnLimpar;
private javax.swing.JButton btnSair;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JList listOnlines;
private javax.swing.JTextArea txtAreaReceive;
private javax.swing.JTextArea txtAreaSend;
private javax.swing.JTextField txtName;
// End of variables declaration
}
Classe ClienteService:
package com.tiete.app.service;
import com.tiete.app.bean.ChatMessage;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Carlos Santana
*/
public class ClienteService {
private Socket socket;
private ObjectOutputStream output;
public Socket connect() {
try {
this.socket = new Socket("localhost", 5555);
this.output = new ObjectOutputStream(socket.getOutputStream());
} catch (UnknownHostException ex) {
Logger.getLogger(ClienteService.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ClienteService.class.getName()).log(Level.SEVERE, null, ex);
}
return socket;
}
public void send(ChatMessage message) {
try {
output.writeObject(message);
} catch (IOException ex) {
Logger.getLogger(ClienteService.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Aplicação Servidor:
Classe Servidor:
package com.tiete.app;
import com.tiete.app.service.ServidorService;
/**
*
* @author Carlos Santana
*/
public class Servidor {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new ServidorService();
}
}
Classe ServidorService:
package com.tiete.app.service;
import com.tiete.app.bean.ChatMessage;
import com.tiete.app.bean.ChatMessage.Action;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
/**
* @author Carlos Santana
*/
public class ServidorService {
private ServerSocket serverSocket;
private Socket socket;
private Map<String, ObjectOutputStream> mapOnlines = new HashMap<String, ObjectOutputStream>();
public ServidorService() {
try {
serverSocket = new ServerSocket(5555);
JOptionPane.showMessageDialog(null, "Servidor online!");
while (true) {
socket = serverSocket.accept();
new Thread(new ListenerSocket(socket)).start();
}
} catch (IOException ex) {
Logger.getLogger(ServidorService.class.getName()).log(Level.SEVERE, null, ex);
}
}
private class ListenerSocket implements Runnable {
private ObjectOutputStream output;
private ObjectInputStream input;
public ListenerSocket(Socket socket) {
try {
this.output = new ObjectOutputStream(socket.getOutputStream());
this.input = new ObjectInputStream(socket.getInputStream());
} catch (IOException ex) {
Logger.getLogger(ServidorService.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
public void run() {
ChatMessage message = null;
try {
while ((message = (ChatMessage) input.readObject()) != null) {
Action action = message.getAction();
switch (action) {
case CONNECT:
boolean isConnect = connect(message, output);
if (isConnect) {
mapOnlines.put(message.getName(), output);
sendOnlines();
} break;
case DISCONNECT:
disconnect(message, output);
sendOnlines();
return;
case SEND_ONE:
sendOne(message);
break;
case SEND_ALL:
sendAll(message);
break;
default:
break;
}
}
} catch (IOException ex) {
ChatMessage cm = new ChatMessage();
cm.setName(message.getName());
disconnect(cm, output);
sendOnlines();
System.out.println(message.getName() + " Desconectou!");
} catch (ClassNotFoundException ex) {
Logger.getLogger(ServidorService.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private boolean connect(ChatMessage message, ObjectOutputStream output) {
if (mapOnlines.isEmpty()) {
message.setText("Aceito");
send(message, output);
message.setText(" Usuário Conectou - se!");
message.setAction(Action.SEND_ONE);
sendAll(message);
return true;
}
if (mapOnlines.containsKey(message.getName())) {
message.setText("Rejeitado");
send(message, output);
return false;
} else {
message.setText("Aceito");
send(message, output);
message.setText(" Usuário Conectou - se!");
message.setAction(Action.SEND_ONE);
sendAll(message);
return true;
}
}
private void disconnect(ChatMessage message, ObjectOutputStream output) {
mapOnlines.remove(message.getName());
message.setText(" Desconectou-se");
message.setAction(Action.SEND_ONE);
sendAll(message);
System.out.println("Usuario " + message.getName() + " saiu da sala");
}
private void send(ChatMessage message, ObjectOutputStream output) {
try {
output.writeObject(message);
} catch (IOException ex) {
Logger.getLogger(ServidorService.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void sendOne(ChatMessage message) {
for (Map.Entry<String, ObjectOutputStream> kv : mapOnlines.entrySet()) {
if (kv.getKey().equals(message.getNameReserved())) {
try {
kv.getValue().writeObject(message);
} catch (IOException ex) {
Logger.getLogger(ServidorService.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
private void sendAll(ChatMessage message) {
for (Map.Entry<String, ObjectOutputStream> kv : mapOnlines.entrySet()) {
if (!kv.getKey().equals(message.getName())) {
message.setAction(Action.SEND_ONE);
try {
kv.getValue().writeObject(message);
} catch (IOException ex) {
Logger.getLogger(ServidorService.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
private void sendOnlines() {
Set<String> setNames = new HashSet<>();
for (Map.Entry<String, ObjectOutputStream> kv : mapOnlines.entrySet()) {
setNames.add(kv.getKey());
}
ChatMessage message = new ChatMessage();
message.setAction(Action.USERS_ONLINE);
message.setSetOnlines(setNames);
for (Map.Entry<String, ObjectOutputStream> kv : mapOnlines.entrySet()) {
message.setName(kv.getKey());
try {
kv.getValue().writeObject(message);
} catch (IOException ex) {
Logger.getLogger(ServidorService.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
Classe ChatMessage (do Servidor):
package com.tiete.app.bean;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
/**
*
* @author Carlos Santana
*/
public class ChatMessage implements Serializable {
private String name;
private String text;
private String nameReserved;
private Set<String> setOnlines;
private Action action;
public ChatMessage() {
this.setOnlines = new HashSet<>();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getNameReserved() {
return nameReserved;
}
public void setNameReserved(String nameReserved) {
this.nameReserved = nameReserved;
}
public Set<String> getSetOnlines() {
return setOnlines;
}
public void setSetOnlines(Set<String> setOnlines) {
this.setOnlines = setOnlines;
}
public Action getAction() {
return action;
}
public void setAction(Action action) {
this.action = action;
}
public enum Action {
CONNECT, DISCONNECT, SEND_ONE, SEND_ALL, USERS_ONLINE
}
}