Bom dia pessoal, tudo bom? Espero que sim…
Estudo redes e estou tendo aulas de programação orientada a objetos com java, meu professor me passou um trabalho de um chat ponto a ponto, usando sockets e swing, deixou o material no site, mas não estou conseguindo montar o programa, vou postar aqui o material que ele disponibilizou, caso alguem consiga fazer o programinha conversar (enviar e receber mensagens) por favor post o resultado aqui, pois estou precisando muito de nota. =D
1- Código fonte do chat:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class ChatPolicamp extends JFrame implements ActionListener{
private JButton b1,b2;
private JTextArea ta1,ta2;
private GridBagConstraints c;
private JCheckBox cb1;
private JScrollPane sp1;
private JScrollPane sp2;
public ChatPolicamp() {
setSize(300, 400);
setVisible(true);
setLayout(new GridBagLayout());
setTitle("Aula - GridBagLayout");
ta1 = new JTextArea(10,30);
sp1 = new JScrollPane(ta1);
ta2 = new JTextArea(5,30);
sp2 = new JScrollPane(ta2);
b1 = new JButton(“OK”);
b1.addActionListener(this);
b2 = new JButton(“Send”);
b2.addActionListener(this);
cb1 = new JCheckBox(“Client”);
c = new GridBagConstraints();
c.anchor = GridBagConstraints.CENTER;
c.fill = GridBagConstraints.NONE;
c.gridwidth =3;
c.gridheight =1;
c.insets = new Insets(5,5,5,5);//Topo, esquerda, base, direita
c.gridx = 0;
c.gridy = 0;
add(sp1,c);
c.gridx = 0;
c.gridy = 1;
add(sp2,c);
c.anchor = GridBagConstraints.LINE_START;
c.gridwidth =1;
c.gridx = 0;
c.gridy = 2;
add(b1,c);
c.gridx = 1;
c.gridy = 2;
add(b2,c);
c.gridx = 2;
c.gridy = 2;
add(cb1,c);
pack();
}
public static void main(String[] args) {
ChatPolicamp cp = new ChatPolicamp();
}
public void actionPerformed(ActionEvent evt) {
if(evt.getSource().equals(this.b1)){
JOptionPane.showMessageDialog(this, "Exemplo de caixa de texto");
}else if (evt.getSource().equals(this.b2)){
ta1.append("[HOME]:"+ta2.getText()+"\n");
ta2.setText("");
}
}
}
2- Escrita e leitura do arquivo:
Escrita:
public void lerArquivo() {
JFileChooser fc = new JFileChooser(System.getProperty(“user.dir”));
int fd = fc.showOpenDialog(this);
try {
if (fd == JFileChooser.APPROVE_OPTION) {
FileOutputStream fo = new FileOutputStream(
fc.getSelectedFile());
PrintStream ps = new PrintStream(fo);
ps.println(ta.getText());
ps.close(); // Fecha a impressao no arquivos
fo.close(); // Fecha o arquivos
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
Leitura:
public void lerArquivo() {
JFileChooser fc = new JFileChooser(System.getProperty(“user.dir”));
int fd = fc.showOpenDialog(this);
try {
if (fd == JFileChooser.APPROVE_OPTION) {
FileInputStream fi = new FileInputStream(fc.getSelectedFile());
BufferedReader br = new BufferedReader(new
InputStreamReader(fi));
String textoDoArquivo;
while ((textoDoArquivo = br.readLine()) != null) {
ta.append(textoDoArquivo+"\n");
}
br.close();
fi.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
3-Socket:
private ServerSocket server;
private Socket client;
private Socket socket;
private BufferedReader inServer;
private BufferedReader inClient;
private PrintWriter out;
? Código
/**
- Inicia o servidor de conexões
/
public void iniciarServidor() {
try {
server = new ServerSocket(4444);
client = server.accept();
inServer = new BufferedReader(new InputStreamReader(client
.getInputStream()));
out = new PrintWriter(client.getOutputStream(), true);
while (true) {
String line = inServer.readLine();
// Le o arquivo e coloca na tela
out.println(line);
this.ta1.append(line + “\n”);
}
} catch (IOException e) {
System.out.println(“Accept failed: 4444”);
System.exit(-1);
}
}
/* - Envia a Mensagem para o servidor
/
public void enviarMensagem(){
String text = “[OUT]:”+ ta2.getText();
out.println(text);
ta2.setText(new String(""));
try {
String line = inClient.readLine();
System.out.println(“Text received :” + line);
} catch (IOException e) {
System.out.println(“Read failed”);
System.exit(1);
}
}
/* - Conecta com o chat cliente
*/
public void connectar(){
// Create socket connection
try {
//Cria a conexão / Socket
socket = new Socket(“192.168.17.129”, 4444);
//Cria um anal para impressão de mensagens
out = new PrintWriter(socket.getOutputStream(), true);
//Cria a o canal de resposta para manter a conexão ativa.
inClient = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
} catch (UnknownHostException e) {
System.out.println(“Unknown host: localhost”);
System.exit(1);
} catch (IOException e) {
System.out.println(“No I/O”);
System.exit(1);
}
}
=======================
4-Iniciar o serviço:
public void iniciarServidor() {
try {
server = new ServerSocket(4444);
client = server.accept();
inServer = new BufferedReader(new InputStreamReader(client
.getInputStream()));
out = new PrintWriter(client.getOutputStream(), true);
while (true) {
String line = inServer.readLine();
out.println(line);
this.ta1.append(line + “\n”);
}
} catch (IOException e) {
System.out.println(“Accept failed: 4444”);
System.exit(-1);
}
}
=======================
5- Enviar mensagem:
public void enviarMensagem(){
String text = “[OUT]:”+ ta2.getText();
out.println(text);
ta2.setText(new String(""));
try {
String line = inClient.readLine();
System.out.println(“Text received :” + line);
} catch (IOException e) {
System.out.println(“Read failed”);
System.exit(1);
}
}
=======================
6-Conexão com o cliente:
public void connectar(){
try {
socket = new Socket(“192.168.17.129”, 4444);
out = new PrintWriter(socket.getOutputStream(), true);
inClient = new BufferedReader(
new InputStreamReader(socket.getInputStream()
));
} catch (UnknownHostException e) {
System.out.println(“Unknown host: localhost”);
System.exit(1);
} catch (IOException e) {
System.out.println(“No I/O”);
System.exit(1);
}
}
=======================
Eu sei que parece complicado incialmente, mais para um programador Java isso deve ser simples de se impkementar.
Desde já agradeço
Regis B.