Subpage under development, new version coming soon!
Subject: Programação
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();
}
}
----------------------------------------------
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();
}
}
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"
------------------------------------------------
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"
tou investigando o problema do servidor de diminuir o contador quando alguem desconectar...
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?
quando da conexão esgotada ele continua abrindo o Frame, tendeu?
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
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
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.
DÁ CARRIM NÃO, MAH!
aahauahuahauhauaha.
Lembrei e ri muito do vídeo sozinho agora.
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)
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)
======================= 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"
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"
======================= 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();
}
}
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();
}
}
======================= 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);
}
}
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);
}
}
======================= 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();
}
}
}
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();
}
}
}
Deixa ele pros outros mods, aqueles que não têm vida social mas manjam um monte dessas letrinhas e outros símbolos. :P
pelo menos dormi até tarde hoje, não ia trabalhar mesmo... hehehe