Azərbaycan dili Bahasa Indonesia Bosanski Català Čeština Dansk Deutsch Eesti English Español Français Galego Hrvatski Italiano Latviešu Lietuvių Magyar Malti Mакедонски Nederlands Norsk Polski Português Português BR Românã Slovenčina Srpski Suomi Svenska Tiếng Việt Türkçe Ελληνικά Български Русский Українська Հայերեն ქართული ენა 中文
Subpage under development, new version coming soon!

Subject: Programação

2009-04-16 03:19:21
Eiro, acho que resolvi o problema da frame. Segue o novo Cliente:
----------------------------------------------
import java.net.*;
import java.io.*;

import javax.swing.JOptionPane;

public class Cliente extends Thread {
Socket socket;
PrintStream out;
FrameCliente frame;
// public static final int PORTA = 1024;
private int PORTA;
public static final String SERVIDOR = "localhost";

public Cliente() {
init();
}

public void init() {
this.PORTA = Integer.parseInt(JOptionPane.showInputDialog("Informe a Porta do Servidor"));
this.socket = new Socket();
frame = new FrameCliente(socket);
frame.setVisible(true);
try {
this.socket.connect(new InetSocketAddress(InetAddress.getByName(SERVIDOR), PORTA));
frame.getTxfArea().setText(frame.getTxfArea().getText() + " Sucesso!");
} catch (Exception ex) {
frame.getTxfArea().setText(frame.getTxfArea().getText() + " Erro!");
System.out.println(ex);
JOptionPane.showMessageDialog(null,"Maximo numero de conexões atingido!","Erro",JOptionPane.ERROR_MESSAGE);
frame.dispose();
init();
}
}

public void run() {
BufferedReader in;
String msg;
while (true) {
try {
if (socket.getInputStream().available() > 0) {
in = new BufferedReader(new InputStreamReader(socket
.getInputStream()));
msg = in.readLine();
frame.txfArea.append(msg + "\n");
}
} catch (Exception ex) {
System.out.println(ex);
}
try {
Thread.sleep(1000);
} catch (Exception ex) {
}
}
}

public static void main(String[] args) {
Cliente cliente = new Cliente();
cliente.start();

}

}
2009-04-16 03:19:51
precisa também de uma atualização no Frame:
------------------------------------------------
import java.awt.BorderLayout;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import java.awt.Rectangle;
import java.awt.Dimension;
import javax.swing.JTextField;
import java.net.*;
import java.io.*;

public class FrameCliente extends JFrame {
Socket socket;
PrintStream out;
private static final long serialVersionUID = 1L;
private JPanel jContentPane = null;
JTextArea txfArea = null;
private JTextField txfMsg = null;

public FrameCliente(Socket socket) {
super();
this.socket = socket;
try {
out = new PrintStream(socket.getOutputStream());
} catch (Exception ex) {
System.out.println(ex);
}
initialize();
}

private void initialize() {
this.setSize(300, 203);
this.setContentPane(getJContentPane());
this.setTitle("JFrame");
}

private JPanel getJContentPane() {
if (jContentPane == null) {
jContentPane = new JPanel();
jContentPane.setLayout(null);
jContentPane.add(getTxfArea(), null);
jContentPane.add(getTxfMsg(), null);
}
return jContentPane;
}

public JTextArea getTxfArea() {
if (txfArea == null) {
txfArea = new JTextArea();
txfArea.setBounds(new Rectangle(1, 1, 288, 135));
txfArea.setText("Tentando conectar com o servidor...");
}
return txfArea;
}

private JTextField getTxfMsg() {
if (txfMsg == null) {
txfMsg = new JTextField();
txfMsg.setBounds(new Rectangle(1, 142, 288, 20));
txfMsg.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
out.println(txfMsg.getText());
txfMsg.setText("");
}
});
}
return txfMsg;
}

} // @jve:decl-index=0:visual-constraint="10,10"
2009-04-16 03:20:22
tou investigando o problema do servidor de diminuir o contador quando alguem desconectar...
2009-04-16 03:32:35
mah... tipo assim, toda vez q eu entro com um cliente ele abre um frame(ex: 5 clientes, 5 frames, 1 pra cada cliente)

quando da conexão esgotada ele continua abrindo o Frame, tendeu?
2009-04-16 04:01:31
agora soh fica naquela Tentando conectar ao servidor e n conecta
tento escrever algo e num aparece nada dps q eu do enter
e continua abrindo os frame dps de esgotado

precisa mudar o servidor tb neh pra ficar do jeito q tu ta fazendo
2009-04-16 04:02:42
blz. tou vendo aqui. vai sair :)
2009-04-16 05:24:31
mah... tipo assim, toda vez q eu entro com um cliente ele abre um frame(ex: 5 clientes, 5 frames, 1 pra cada cliente)

DÁ CARRIM NÃO, MAH!
aahauahuahauhauaha.

Lembrei e ri muito do vídeo sozinho agora.
2009-04-16 08:36:40
uhahuahu pensei a mesmissima coisa

Eiro, meu velho. Demorou mas saiu. Entretanto, tive que fazer algumas mudanças no teu código em função dos requisitos do professor. Vamos por partes:

1- Dei uma pesquisada e é impossível saber que um socket foi desconectado, por java, em runtime. O sistema precisa ter controle disso, pois a máquina virtual sempre vai escalar para o sistema operacional dizer se o socket tá em uso ou não. De certa forma, embora não tivesse sido a intenção dele, o ferdam explicou isso acima. No caso do windows, o SO nunca considera um socket encerrado, a não ser que o teu programa diga: encerre este socket.
2- Por causa disso, adicionei um método de controle no servidor, chamado closeServerConnection(socket s) - ele remove o socket da lista de controle, diminui o número de conexões ativas e volta o servidor para o estado de listening.
3- O Cliente não precisa ser implementado em threads... cada classe é uma instância de cliente. Não faz mto sentido isso, na verdade...
4- O Servidor não pode ser uma instância de Threads também, senão não há como controlar o número total de conexões. O servidor precisa ser um loop de alto nível, que ativa as Threads para cada requisição de conexão de algum Cliente...
5- Por isso, criei uma classe nova, que extende de Thread, chamada ThreadConexao. Toda vez que um cliente tenta se conectar com o servidor, uma nova ThreadConexao é criada e serve como interface cliente/servidor.
6- A única forma de detectar que o número máximo de conexões foi atingido e rejeitar a conexão é trazendo o controle para o protocolo de conexão. Por isso, creiei uma palavra "MAXCONN" - quando o servidor vê que o numero maximo foi atingido, manda um booleano para a ThreadConexao dizendo que esta conexão não pode ser estabelecida. ThreadConexao repassa a msg para o Cliente, que dá dispose na frame e re-abre o InputDialog para que o Cliente tente se conectar novamente (foi isso que você me pediu, né?).
7- Adicionei uma outra palavra reservada, "Exit". Se o cliente digitar Exit, o servidor desconecta ele.
8- Adicionei um listener na JFrame para que: se o usuario no cliente fechar a janela, o cliente envia "Exit" e o servidor fecha a conexão de maneira segura.
9- Qualquer outra palavra digitada na Frame vai ser repetida pelo Servidor.

As classes seguem abaixo:
(edited)
2009-04-16 08:37:43
======================= FrameCliente.java ==========================

import java.awt.BorderLayout;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import java.awt.Rectangle;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JTextField;
import java.net.*;
import java.io.*;

public class FrameCliente extends JFrame {
Socket socket;
PrintWriter out;
private static final long serialVersionUID = 1L;
private JPanel jContentPane = null;
JTextArea txfArea = null;
private JTextField txfMsg = null;

public FrameCliente(Socket socket, PrintWriter out) {
super();
this.socket = socket;
try {
this.out = out;
} catch (Exception ex) {
System.out.println(ex);
}
initialize();
}

private void initialize() {
this.setSize(300, 203);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
out.println("Exit");
System.exit(0);
}
});
this.setContentPane(getJContentPane());
this.setTitle("JFrame");
}

private JPanel getJContentPane() {
if (jContentPane == null) {
jContentPane = new JPanel();
jContentPane.setLayout(null);
jContentPane.add(getTxfArea(), null);
jContentPane.add(getTxfMsg(), null);
}
return jContentPane;
}

public JTextArea getTxfArea() {
if (txfArea == null) {
txfArea = new JTextArea();
txfArea.setBounds(new Rectangle(1, 1, 288, 135));
txfArea.setText("Inicializando conexão...");
}
return txfArea;
}

private JTextField getTxfMsg() {
if (txfMsg == null) {
txfMsg = new JTextField();
txfMsg.setBounds(new Rectangle(1, 142, 288, 20));
txfMsg.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
// palavra reservada ao sistema: adicionar mais no futuro
if (txfMsg.getText().equals("MAXCONN")) {
txfArea.append("\nErro! Favor usar palavra não reservada");
} else {
out.println(txfMsg.getText());
txfArea.append("\nClient: " + txfMsg.getText());
}
txfMsg.setText("");
}
});
}
return txfMsg;
}

} // @jve:decl-index=0:visual-constraint="10,10"
2009-04-16 08:38:14
======================= Cliente.java ==========================
import java.net.*;
import java.io.*;

import javax.swing.JOptionPane;

public class Cliente {
Socket socket;
PrintWriter out = null;
BufferedReader in = null;

FrameCliente frame;
// public static final int PORTA = 1024;
private int PORTA;
public static final String SERVIDOR = "localhost";

public Cliente() {
init();
}

public void init() {
try {
this.PORTA = Integer.parseInt(JOptionPane
.showInputDialog("Informe a Porta do Servidor"));
socket = new Socket();
socket.connect(new InetSocketAddress(InetAddress
.getByName(SERVIDOR), PORTA));
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket
.getInputStream()));

frame = new FrameCliente(socket, out);
frame.setVisible(true);

String fromServer;

while ((fromServer = in.readLine()) != null) {
frame.txfArea.append("\nServer: " + fromServer);

if (fromServer.equals("MAXCONN") || fromServer.equals("Exit"))
break;
// TODO: Adicionar outras mensagens
}

if (fromServer.equals("MAXCONN")) {
JOptionPane.showMessageDialog(null,
"Maximo numero de conexões já atingido!", "Erro",
JOptionPane.ERROR_MESSAGE);
System.out.println("Capacidade de Conexões Esgotada.");
frame.txfArea
.append("\nServer: Maximo numero de conexões já atingido! \n");
frame.dispose();
new Cliente();

} else if (fromServer.equals("Exit")) {
System.out.println("Cliente desconectado");
frame.txfArea.append("\nServer: Good bye!\n");
frame.dispose();
}

in.close();
socket.close();
out.close();

} catch (UnknownHostException e) {
System.err.println("Problema no host: localhost.");
System.exit(1);
} catch (IOException e) {
System.err.println("I/O exception para localhost.");
System.exit(1);
}
}

public static void main(String[] args) {
new Cliente();
}

}
2009-04-16 08:38:43
======================= Servidor.java ==========================

import java.net.*;
import java.util.*;
import java.io.*;

import javax.swing.*;

public class Servidor {
ServerSocket srvSocket;
int totalClientes;
// public static final int PORTA = 1024;
private int PORTA, NUMCLIENTE;
ArrayList<Socket> listaClientes;

public Servidor(int port, int numcli) {
this.PORTA = port;
this.NUMCLIENTE = numcli;
System.out.println("Iniciando servidor...");

try {
srvSocket = new ServerSocket(this.PORTA);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
totalClientes = 0;
listaClientes = new ArrayList<Socket>();

aguardarClientes();
}

public void aguardarClientes() {
try {
while (true) { // inicializa as threads
System.out.println("Aguardando conexões na porta " + PORTA
+ "...");
Socket s = srvSocket.accept();
if (totalClientes < NUMCLIENTE) {
// numero maximo de conexoes nao atingido
new ThreadConexao(s, false, this).start();
listaClientes.add(s);
totalClientes++;
} else {
// numero maximo de conexoes já atingido
new ThreadConexao(s, true, this).start();
}
System.out.println(totalClientes + " conectados");

}
} catch (Exception ex) {
System.out.println(ex);
System.exit(1);
}

}

public void closeServerConnection(Socket s) throws IOException {
Iterator<Socket> itOrigem;
itOrigem = listaClientes.iterator();
while (itOrigem.hasNext()) {
// necessario identificar quando um socket desconectou
if (itOrigem.next().equals(s)) {
totalClientes--;
System.out.println(totalClientes + " conectados");
listaClientes.remove(s);
break;
}
}
//aguardarClientes();
}

public static void main(String[] args) {
int p, n;
p = Integer.parseInt(JOptionPane
.showInputDialog("Informe a Porta do Servidor"));
n = Integer.parseInt(JOptionPane
.showInputDialog("Informe a Quantidade Máxima de Clientes"));
new Servidor(p, n);
}
}
2009-04-16 08:39:12
======================= ThreadConexao.java ==========================

import java.net.*;
import java.io.*;

public class ThreadConexao extends Thread {
private Socket socket = null;
private Servidor parent;
boolean isMax = false;

public ThreadConexao(Socket socket, boolean isMax, Servidor parent) {
super("ThreadConexao");
System.out.println("Conexao aceita de: " + socket.getInetAddress()
+ ":" + socket.getPort());
this.socket = socket;
this.isMax = isMax;
this.parent = parent;
}

public void run() {

try {
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket
.getInputStream()));

String inputLine, outputLine;
outputLine = null;
if (this.isMax) { // conexão será rejeitada
outputLine = "MAXCONN";
out.println(outputLine);
} else {
while ((inputLine = in.readLine()) != null) {
outputLine = inputLine;
out.println(outputLine);
if (outputLine.equals("Exit"))
break;

Thread.sleep(1000);
}
}
out.close();
in.close();
socket.close();
if (outputLine.equals("Exit"))
parent.closeServerConnection(socket);

} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}
2009-04-16 08:39:34
boa sorte com o resto do exercicio :)
2009-04-16 16:00:31
Kct, eu entro nesse tópico, fico até tonto!
2009-04-16 16:05:49
Deixa ele pros outros mods, aqueles que não têm vida social mas manjam um monte dessas letrinhas e outros símbolos. :P
2009-04-16 17:55:57
pelo menos dormi até tarde hoje, não ia trabalhar mesmo... hehehe