Salve galera!
Abaixo posto um código, sobre o qual já trabalhei um bocado, que já modifiquei várias vezes.
É um pequeno servidor, que recebe o login, se for o correto lança uma thread e tals…
Acho que não é das melhores práticas como está exposto abaixo, utilizando strings para comunicação, mas essa é apenas mais uma versao do servidor. O que acontece é que quando lanço a thread, ele aponta:
Conexao normal
java.net.SocketException: Socket is closed
at java.net.Socket.getOutputStream(Unknown Source)
at Servidor.run(Servidor.java:136)
a 136 é a ObjectInputStream istream = new ObjectInputStream(conexao2.getInputStream());
Já tentei dar flush(), close() e tudo mais… o engraçado é que quando dou ostream.close() por exemplo, cai o socket todo, depois da thread também… li também que o ostream e o istream devem ser recriados a cada envio(???)…
Bom, posto ae pra vcs darem uma olhada e sugerirem algo.
valeu ae!
public class Servidor extends Thread{
static Connection cmysql = null;
Socket conexao2;
ObjectOutputStream ostream = null;
ObjectInputStream istream = null;
String nomeT = new String("Servidor 0");
public void eO(Object j){
try{
ostream.writeObject(j);
ostream.flush();
System.out.println(j.toString());
}
catch(Exception e){
e.printStackTrace();
}
}
public String getNomeT(){
return nomeT;
}
public void setNomeT(String n){
nomeT = n;
}
public static void main(String args[]){
try {
ServerSocket sv = new ServerSocket(8000);
int serv = 1;
while (true) {
System.out.print("Esperando alguem se conectar...");
Socket conexao = sv.accept();
System.out.println(" Conectou!");
ObjectOutputStream ostream0 = new ObjectOutputStream(conexao.getOutputStream());
ObjectInputStream istream0 = new ObjectInputStream(conexao.getInputStream());
try{
String[] a = (String[])istream0.readObject();//1
System.out.println("Lidos " + a[0] + a[1] + a[2]);
int tipo = Integer.valueOf(a[0]);
String user = a[1];
String pass = a[2];
String autorizado = new String("não");
switch(tipo){
case 1:
try{
if(Login(user, pass)){
autorizado = "sim";
System.out.println("Nova thread");
Thread t = new Servidor(conexao, "Servidor " + serv);
t.start();
serv = serv+1;
}
// ostream.flush();
}
catch(Exception e){e.printStackTrace();
System.out.println("Conexão não aceita");
autorizado = "não";
}
break;
case 2000:
System.out.println("Conexao errada");
break;
}
ostream0.writeObject(autorizado);//4
}
catch(Exception e){e.printStackTrace();
String n = new String("Erro");
ostream0.writeObject(n);//4
}
}
}
catch (IOException e) {
System.out.println("IOException: " + e);
}
}
public Servidor(Socket s, String n){
conexao2 = s;
setNomeT(n);
}
public void run(){
try{
System.out.println(getNomeT());
while(true){
if(conexao2!=null){
System.out.println("Conexao normal");
}
ObjectOutputStream ostream = new ObjectOutputStream(conexao2.getOutputStream());
ObjectInputStream istream = new ObjectInputStream(conexao2.getInputStream());
String[] s = (String[])istream.readObject();
int tipo = Integer.valueOf(s[0]);