Ver Mensaje Individual
  #4 (permalink)  
Antiguo 21/12/2010, 10:35
oscardelphi
 
Fecha de Ingreso: octubre-2010
Mensajes: 27
Antigüedad: 13 años, 6 meses
Puntos: 2
Respuesta: Que necesito Leer para hacer un chat

Hola calichecal,

Una vez hice un Chat, el servidor estaba en Java java dooo (Linux) y el cliente en Delphi (Windows).

Y bueno como el conocimiento es compartir ahi va el código, si lo mejoras te lo agradeceria, cualquier cosa estoy en [email protected].

Saludos

Manuel

Clase: ServidorChat.java
public class ServidorChat extends javax.servlet.http.HttpServlet{
static{
(new Servidor()).start();
}
}
class Servidor extends Thread{
public void run(){
try{
List clientes=new Vector();
ServerSocket serverSocket = null;
boolean listening=true;

serverSocket = new ServerSocket(4444);

System.out.println("-- Iniciado el servidor de chat" );
//int sg=0;
while (listening){
//System.out.println("sg: "+sg++);
ThreadServer cliente=null;
clientes.add( cliente=new ThreadServer(serverSocket.accept(),clientes));
cliente.start();
}

serverSocket.close();
}catch(Exception ex){
System.err.println("["+(new java.util.Date(System.currentTimeMillis()))+"]"+ex.getMessage());
ex.printStackTrace();
}
}
}

Clase: ThreadServer.java
public class ThreadServer extends Thread{
private Socket socket = null;
private java.util.List lista=null;
private String usuario;
private PrintWriter out;
private BufferedReader in;
private String grupo,sql;
private Conexion con=new Conexion();
public void run() {

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

String inputLine, outputLine;
//recibiendo información del usuario

while ((inputLine = in.readLine()) != null) {
System.out.println("Valor enviado por el Cliente: "+inputLine);

StringTokenizer st=new StringTokenizer(inputLine,";");
while (st.hasMoreTokens()){
String fUsuario=st.nextToken();
StringTokenizer st0=new StringTokenizer(fUsuario,":");
String t=st0.nextToken();
if (t.equalsIgnoreCase("usuario"))
this.usuario=st0.nextToken();
else if (t.equalsIgnoreCase("grupo"))
this.grupo=st0.nextToken();

}
break;
}
//verificando que no se repita el usuario, si existe, sacarlo de la lista.
for(Iterator i=lista.iterator();i.hasNext();){
ThreadServer thread=(ThreadServer)i.next();
if (thread.getUsuario().equals(this.usuario) && !thread.equals(this)){
thread.destroy();
break;
}
}

//enviando la lista de usuarios conectados;
String usuarios="";
for(Iterator i=lista.iterator();i.hasNext();){
ThreadServer thread=(ThreadServer)i.next();
if (thread.getGrupo().equalsIgnoreCase(this.grupo))
usuarios+=thread.getUsuario()+",";
}
out.println("%%getList,"+usuarios);

//notificar a los demás que entró un nuevo usuario
java.util.Date hora=new java.util.Date(System.currentTimeMillis());
for(Iterator i=lista.iterator();i.hasNext();){
ThreadServer thread=(ThreadServer)i.next();
if (thread.getGrupo().equalsIgnoreCase(this.grupo) && !thread.getUsuario().equalsIgnoreCase(usuario)){
thread.escribir("%%addUser,"+usuario);

thread.escribir("** ["+hora+"] "+usuario+" acaba de ingresar **");
}
}

boolean salir=false;

this.escribir(" ** Bienvenido a la sala de conversación ** ");

while ((inputLine = in.readLine()) != null && !(salir=inputLine.equals("/q"))) {
for(Iterator i=lista.iterator();i.hasNext();){
ThreadServer thread=(ThreadServer)i.next();
String sGrupo = thread.getGrupo();
String sUsuario = thread.getUsuario();
if (thread.getGrupo().equalsIgnoreCase(grupo))
if (inputLine.startsWith("%%"))
thread.escribir(inputLine);
else
thread.escribir(usuario,inputLine,sGrupo,sUsuario, socket.getInetAddress().getHostAddress());
}

}


} catch (IOException e) {
e.printStackTrace();

}catch(NullPointerException e){
System.out.println("--Error de usuario entrante ("+socket.getInetAddress().getHostAddress()+"). . desconectándolo");
}

this.destroy();
}
public ThreadServer(Socket socket, java.util.List lista) {
super("ThreadServer"); //TheardServer
this.socket = socket;
this.lista=lista;
System.out.println("["+(new java.util.Date(System.currentTimeMillis()))+"]--Hay una nueva conexion");
mostrarEstadoConexiones();
}
void mostrarEstadoConexiones(){
System.out.println( "("+lista.size()+" conexiones activas)");
}
protected void escribir(String remitente,String texto,String grupo, String usua, String ipRemitente) {
out.println(remitente+" >"+texto);
//aquí se va a grabar todos los datos
if (!usua.equalsIgnoreCase(remitente)){
sql = "insert into mensajechat (sala,usuarioOrigen,usuarioDestino,mensaje, fecha,publico, hostOrigen,hostDestino) values (\""+grupo+"\",\""+remitente+"\",\""+usua+"\",\""+ texto+"\",now(),\"S\",\""+ipRemitente+"\",'"+socke t.getInetAddress().getHostAddress()+"')";
sql = sql.replace('\"','\'');
java.sql.ResultSet rs = con.executeQuery(sql);
}
}
protected void escribir(String texto){
out.println(texto);
}
public void destroy() {
try{
java.util.Date hora=new java.util.Date(System.currentTimeMillis());
if (lista.remove(this)){
this.escribir(" ** Ha dejado la sala de conversación ** ");
for(Iterator i=this.lista.iterator();i.hasNext();){
ThreadServer thread=(ThreadServer)i.next();
if (this.grupo.equalsIgnoreCase(thread.grupo)){
thread.escribir("** ["+hora+"] "+usuario+" ha dejado la sala **");
thread.escribir("%%exitUser,"+this.usuario);
}
}
out.close();
in.close();
socket.close();
System.out.println("["+(new java.util.Date(System.currentTimeMillis()))+"]--Finalizando "+this.usuario);
mostrarEstadoConexiones();
}
}catch(java.io.IOException ex){
ex.printStackTrace();
}
}
public String getUsuario() {
return usuario;
}
public String getGrupo() {
return grupo;
}
}

Clase: TestServidorChat.java
public class TestServidorChat {
public static void main(String[] args) {
(new Servidor()).start();
}
}

Saludos

Manuel