quarta-feira, 7 de setembro de 2011

Um simples chat (Exemplo simples de socket Multithread) em java

Segue abaixo um exemplo modificado do site:
http://www.ase.md/~aursu/ClientServerThreads.html







O código do Servidor:

/* http://www.ase.md/~aursu/ClientServerThreads.html */

import java.io.*;
import java.net.*;
public class MultiThreadChatServerDM1{
static Socket clientSocket = null;
static ServerSocket serverSocket = null;
static clientThread t[] = new clientThread[10];
public static void main(String args[]) {
int port_number=2222;
if (args.length < 1)
{
System.out.println("Use: java MultiThreadChatServerDM1 \n"+
"Agora usando a porta ="+port_number);
} else {
port_number=Integer.valueOf(args[0]).intValue();
}
try {
serverSocket = new ServerSocket(port_number);
}
catch (IOException e){System.out.println(e);}
while(true){
try {
clientSocket = serverSocket.accept();
for(int i=0; i<=9; i++){
if(t[i]==null)
{
(t[i] = new clientThread(clientSocket,t)).start();
break;
}
}
}
catch (IOException e) {
System.out.println(e);}
}
}
}
class clientThread extends Thread{
BufferedReader is2=null;
PrintStream os = null;
Socket clientSocket = null;
clientThread t[];
public clientThread(Socket clientSocket, clientThread[] t){
this.clientSocket=clientSocket;
this.t=t;
}
public void run()
{
String line;
String name;
try{
is2= new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
os = new PrintStream(clientSocket.getOutputStream());
os.println("Entre com seu nome.");
name = is2.readLine();
os.println("Oi "+name+" bem vindo ao chat .\nPara mandar a mensagem tecle [enter]\n Para sair Digite \"/quit\" e de [enter] ");
for(int i=0; i<=9; i++)
if (t[i]!=null && t[i]!=this)
t[i].os.println("*** O usuário "+name+" entrou no chat !!! ***" );
while (true) {
line = is2.readLine();
if(line.startsWith("/quit")) break;
for(int i=0; i<=9; i++)
if (t[i]!=null) t[i].os.println("<"+name+"> "+line.toUpperCase());
}
for(int i=0; i<=9; i++)
if (t[i]!=null && t[i]!=this)
t[i].os.println("*** O usuário "+name+" deixou o chat !!! ***" );
os.println("*** Tchau "+name+"! ***");
for(int i=0; i<=9; i++)
if (t[i]==this) t[i]=null;
is2.close();
os.close();
clientSocket.close();
}
catch(IOException e){
};
}
}
O código do cliente:
/* http://www.ase.md/~aursu/ClientServerThreads.html */
import java.io.*;
import java.net.*;
public class MultiThreadChatClientDM1 implements Runnable{
static Socket clientSocket = null;
static PrintStream os = null;
static BufferedReader is2=null;
static BufferedReader inputLine = null;
static boolean closed = false;
public static void main(String[] args) {
int port_number=2222;
String host="localhost";
if (args.length < 2)
{
System.out.println("Use: java MultiThreadChatClientDM1 \n"+"Agora usando host="+host+", porta="+port_number);
} else {
host=args[0];
port_number=Integer.valueOf(args[1]).intValue();
}
try {
clientSocket = new Socket(host, port_number);
inputLine = new BufferedReader(new InputStreamReader(System.in));
os = new PrintStream(clientSocket.getOutputStream());
is2= new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Eu não conheço o host "+host);
} catch (IOException e) {
System.err.println(" Não foi possível conectar ao host "+host);
}
if (clientSocket != null && os != null && is2 != null) {
try {// cria uma thread para ler do server
new Thread(new MultiThreadChatClientDM1()).start();
while (!closed) {
os.println(inputLine.readLine());
}
os.close();
is2.close();
clientSocket.close();
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
public void run() {
String responseLine;
try{
while ((responseLine = is2.readLine()) != null) {
System.out.println(responseLine);
if (responseLine.indexOf("SAIMERDA") != -1) break;//sai do chat se digitar saimerda
}
closed=true;
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}

Aproveitando o embalo o Código te teste de leitura de alquivo verificação do ip através do domínio ...
Objeto RIP(RespostaComOIP):
import java.io.*;

import java.nio.*;

import java.util.*;

import java.net.*;

public class RIP{

private long tm, tn;

private String ip="", host;

private InetAddress ips[];

private boolean sucesso;

private boolean setIpsINetAddr()

{

long tim, tin, tfm, tfn;

int i;

tim=System.currentTimeMillis();

tin=System.nanoTime();

try{



this.ips=InetAddress.getAllByName(this.host);

tfn=System.nanoTime();

tfm=System.currentTimeMillis();

this.tm=tfm-tim;

if(this.tm<=0)

this.tn=tfn-tin;

this.ip+="Ip(s) do host: \""+this.host+"\":\n";

for(i=0; i<ips.length; i++)

{

if(this.tm>0)

this.ip=""+this.host+" - "+this.ips[i].getHostAddress()+" ( "+this.tm+" ms "+")\n";

else

this.ip=""+this.host+" - "+this.ips[i].getHostAddress()+" ("+this.tn+" ns "+")\n";

}

}catch(UnknownHostException ex)

{

if(this.ip.length()<3)

{

tfn=System.nanoTime();

tfm=System.currentTimeMillis();

this.tm=tfm-tim;

this.tn=tfn-tin;

if(this.tm>0)

this.ip+=""+this.host+" - Nome não nao encontrado"+"( "+this.tm+" ms )"+" \n";

else

this.ip+=""+this.host+" - Nome não nao encontrado"+"( "+this.tn+" ns )"+" \n";

}

return false;

}

return true;

}

public String getIp()

{

this.sucesso=this.setIpsINetAddr();

return this.ip;

}

public String getIp1()

{

return this.ip;

}

public String getHost()

{

return this.host;

}

public String getIp(String host1)

{

if(host1.length()>4 && host1!=null)

{

this.host=host1;

return this.getIp();

}

return null;

}

public boolean getOkIp(){return this.sucesso;}

public long getTm(){if(this.tm>0)return this.tm; else return 0L;}

public long getTn(){if(this.tn>0)return this.tn; else return 0L;}

public RIP(String host){this.getIp(host);}

}


Objeto A5 a classe que testa ele e muitas outras coisas:

import java.io.*;

import java.nio.*;

import java.util.*;

import java.net.*;

import java.util.concurrent.TimeUnit;

public class A5

{

static InetAddress ips[], ip1;

static String f, fw, linha=null, hostserv;

static File fi;

static FileWriter writer;

static PrintWriter saida;

static FileReader reader;

static BufferedReader leitor;

static int porta;

static Scanner teclado = new Scanner(System.in);



public static void testeHostIp()throws SecurityException, UnknownHostException

{

int i, j;

String host1="www.google.com.br";

String host4="192.168.2.100";

String host3="www.presenteperfeito.99k.org";

String host2="www.br.yahoo.com";

String hostn =host4+","+host3+","+host2+","+ "www.das.ufsc.br,www.joinville.udesc.br,www.caralho.com.br,www.porra.com";

/*String[] hosts={ host3, host4, host1, host2, "www.das.ufsc.br", "www.joinville.udesc.br"/*, "www.jw.org", "www.wix.com", "www.wix.com/erikabedin/presenteperfeito", "www.terra.com.br", "www.bol.uol.com.br", "www.uol.com.br", "www.ig.com.br", "www.oracle.com", "intranet.softexpert.com", "www.softexpert.com.br", "www.softexpert.com", "www.gvt.com.br", "www.oi.com.br", "www.tim.com.br", "www.microsoft.com", "www.aol.com", "www.locaweb.com.br", "www.registro.br", "www.arin.net", "www.mspc.eng.br", "www.w3schools.com", "php.net", "www.criarweb.com", "www.caralho.com", "www.caralho.com.br", "www.porra.com"};

*/

String[] hosts=hostn.split(",");

//System.out.println(getIpsDosHostsDM2(hosts));

System.out.println(getIpsDosHostsDM4(hosts));

}

public static void IpsDosHostsDM6(String hosts)throws SecurityException, UnknownHostException

{

String[] host=hosts.split(",");

System.out.println(getIpsDosHostsDM4(host));

}

public static String getStrIpsDosHostsDM6(String hosts)throws SecurityException, UnknownHostException

{

String[] host=hosts.split(",");

return getIpsDosHostsDM4(host);

}

public static String getIpsDosHostsDM1(String hosts[])

{

int i;

String s;

s="";

for(i=0; i<hosts.length;i++)

{

s+=getIpsDoHostDM2(hosts[i])+"\n";

}

return s;

}

public static String getIpsDosHostsDM2(String hosts[])

{

int i;

String s;

s="";

for(i=0; i<hosts.length;i++)

{

RIP r = new RIP(hosts[i]);

if(r.getOkIp())

s+=r.getIp()+"\n";

else s+=" Opa não deu pra acessar o host \""+hosts[i]+"\""+"\n"+r.getIp()+"\n\n";

}

return s;

}

public static String getIpsDosHostsDM3(String hosts[])

{

int i;

ArrayList<RIP> rl = new ArrayList<RIP>();

String s;

s="";

for(i=0; i<hosts.length;i++)

{

RIP r = new RIP(hosts[i]);

rl.add(r);

if(r.getOkIp())

s+=r.getIp()+"\n";

else s+=" Opa não deu pra acessar o host \""+hosts[i]+"\""+"\n"+r.getIp()+"\n\n";

}

/* preenche a lista primeiro */



for(i=0; i<hosts.length;i++)

{

RIP r = new RIP(hosts[i]);

if(r.getOkIp()==true)

s+=r.getIp()+"\n";

else s+=" Opa não deu pra acessar o host \""+hosts[i]+"\""+"\n"+r.getIp()+"\n\n";

}

return s;

}

public static String getIpsDosHostsDM4(String hosts[])

{

int i;

ArrayList<RIP> rl = new ArrayList<RIP>();

String s;

s="";

if(setListaDehosts( rl , hosts)>0)

{

s+=getStrlistarListahosts( rl );

}

return s;

}

public static int setListaDehosts(ArrayList<RIP> rl , String hosts[])

{

int i;

for(i=0; i<hosts.length;i++)

{

RIP r = new RIP(hosts[i]);

rl.add(r);

}

return rl.size() ;

}

public static void printStrlistarListahosts(ArrayList<RIP> rl )

{

System.out.println(getStrlistarListahosts(rl));

}

public static String getStrlistarListahosts(ArrayList<RIP> rl )

{

String s="";

int i, a=0,b,c;

float d;

long soma, somans=0, somams=0;

b=(int)rl.size();

for(i=0; i<b;i++)

{

if(rl.get(i).getOkIp()){

s+=rl.get(i).getIp1()+"";a++;}

else{ s+=rl.get(i).getIp1()+""; }

if(rl.get(i).getTm()>0L){

somams+=rl.get(i).getTm();

}else{

if(rl.get(i).getTn()>0L){

somans+=rl.get(i).getTn();

}

}

}

soma = TimeUnit.MILLISECONDS.convert(somans, TimeUnit.NANOSECONDS)+somams;

s+="Tempo total:"+soma+" ms ( media por consulta="+(soma/(long)b)+" ms ) \n";

c=(a/b);

d=((float)a/(float)b);

d=d*(float)100;

s+=d+"% de consultas com sucesso"+"\n\n";

return s;

}

public static String getIpsDoHostDM2(String host)

{



int j;

long ti,tim, tf,tfm, tr, trm;

String s;

s="";

try{

ti= System.nanoTime();

tim=System.currentTimeMillis();

InetAddress ips1[]=InetAddress.getAllByName(host);

tfm= System.currentTimeMillis();

tf=System.nanoTime();

tr=tf-ti;

trm=tfm-tim;

s+="Ip do host:\""+host+"\":\n";

for(j=0; j<ips1.length; j++)

{

s+="ips["+j+"]=\""+ips1[j].getHostAddress()+"\" trm="+trm+"ms "+" tr="+tr+" ns "+"\n";

}

}catch(UnknownHostException ex){

s+="O Ip do host:\""+host+"\" não existe! \n";

}

return s;

}



public static void testeDeLeituraDoTeclado()

{

String lido;

System.out.println("\n Teste de leitura de teclado \n Digite algo:");

lido=teclado.nextLine();

System.out.println("você digitou:\""+lido+"\"");

}

public static void mostrarArrayArgs(String args[])

{

int i;

for(i=0;i<args.length; i++)

{

System.out.println("args["+i+"]=\""+args[i]+"\"");

}

}

public static void atribuiNomeDoArquivoDeLeitura(String args[])

{

if(args.length==0)

{

f="arquivoTesteDM.txt";

}

if(args.length>0)

{

f=args[0];

}

System.out.println(" Arquivo(f):\""+f+"\"");

}

public static void atribuiNomeDoArquivoDeLeitura2(String args[])

{

if(args.length<3)

{

f="t.txt";

}

if(args.length>2)

{

f=args[2];

}

System.out.println(" Arquivo(f):\""+f+"\"");

}

public static void atribuiNomeHostServidor(String args[])

{

if(args.length<1)

{

hostserv="localhost";

}

if(args.length>0)

{

hostserv=args[0];

}

try{

InetAddress ip10=InetAddress.getByName(hostserv);

if(ip10.isLoopbackAddress())

{

hostserv=ip10.getHostAddress();

}

else{

hostserv= ip10.getHostAddress();

}

}catch(UnknownHostException ex){

System.out.println("Nome do servidor:\""+hostserv+"\" não encontrado");

}



System.out.println(" Servidor:\""+hostserv+"\"");

}

public static void atribuiPortaServidor(String args[])

{

if(args.length<2||Integer.parseInt(args[1])<1024)

{

porta=9700;

}

if(args.length>1)

{

porta=Integer.parseInt(args[1]);

}

System.out.println(" porta\""+porta+"\"");

}

public static void atribuiNomeDoArquivoDeEscrita(String args[])

{

if(args.length==0||args.length<2)

{

fw="arquivoTesteEscritaDM.txt";

}

if(args.length>1)

{

fw=args[1];

}

System.out.println(" Arquivo(fw):\""+fw+"\"");

}



public static void testeArquivoLeituraEscrita(String arq)throws IOException

{

String s;

int i;

writer = new FileWriter(fw);

saida = new PrintWriter(writer, true);

saida.println("Eu te amo demais bebê!");

saida.close();

writer.close();

reader = new FileReader(f);

leitor = new BufferedReader(reader, 1*1024*1024);

s="["+f+"];\n[[\"";

i=0;

linha=leitor.readLine();

while((linha != null ))

{//o fim do arquivo sempre tem null

s+="["+i+"]=\""+linha+"\"\n";

linha=leitor.readLine();

i++;

}

s+="["+i+"][\"Último Caractere que fez sair do while\"]=\""+linha+"\"\n";

s+="\"]]\n";

System.out.println(s);

}

public static void testeArquivoLeitura2(String args[])

{

String s;

int i;

atribuiNomeDoArquivoDeLeitura2(args);

atribuiNomeHostServidor(args);

atribuiPortaServidor(args);

s="";

try{

reader = new FileReader(f);

leitor = new BufferedReader(reader, 1*1024*1024);

linha=leitor.readLine();

while((linha != null ))

{

s+=linha+",";

linha=leitor.readLine();

}

s=s.substring(0,s.lastIndexOf(","));

IpsDosHostsDM6(s);



}catch(IOException ie)

{

s+="\n Erro de leitura de arquivo! \n O arquivo \""+f+"\" não existe! \n";

System.out.println(s);

}



}

public static void main(String args[])throws IOException

{

// atribuiNomeDoArquivoDeLeitura(args);

// atribuiNomeDoArquivoDeEscrita(args);

// mostrarArrayArgs(args);

// testeArquivoLeituraEscrita(null);

//testeHostIp();

testeArquivoLeitura2(args);

}

}


Para compilar essas classes java:
javac MultiThreadChatClientDM1.java -Xlint;
javac MultiThreadChatServerDM1.java -Xlint;
javac A5.java ; javac RIP.java

Para executar o chat
gnome-terminal --working-directory=$PWD
Nessa tela de console nova que abriu digite:
java MultiThreadChatServerDM1
Na antiga digite:
java MultiThreadChatClientDM1
gnome-terminal --working-directory=$PWD
Agora na outra tela pra executar o A5:
java A5 localhost 9790 t.txt



Tudo isso está zipado em:
Baixeo_zip

0 comentários: