instrumentos más eficaces y con más solera de Internet. Navegantes y navegantes pasan noches
insomnes en chat IRC o ICQ, en una búsqueda continua de experiencias humanas que la realidad
no virtual difícilmente aporta. Dejando a un lado el aspecto sociológico, a nosotros nos interesa
explicar cómo poner a disposición gratuitamente en los propios sitios una WebChat (chat a la que
se llega desde WWW sin el uso de programas client como mIRC).
Antes de nada conviene precisar que algunas Community incluyen entre sus servicios la posibilidad
de incorporar una Chat. Entre estos Xoom.it se distingue por una excelente interfaz gráfica así
como por una también óptima velocidad de transmisión. Por desgracia, sólo los usuarios Xoom
pueden servirse de esta chat, que no puede ser exportada a otros web. Para mayores detalles,
consulta la página de Xoom.it.
Para una solución universal, es decir, independiente de la localización del servidor, te aconsejamos
el programa Java que utiliza HTMLpoint en su sitio y al que se llega haciendo clic en este enlace.
Se trata de un chat en Java creado por un programador alemán y cuyo .class es directamente
enlazable desde el "sitio madre" y posee las siguientes características:
Una vez introducido este código en tu sitio, tendrás la posibilidad de chatear con tus visitantes.
Cuando se abre el chat, aparece una ventana de pop-up en la que se ven pancartas comerciales
del creador del programa.
import java.net.*;
import java.io.*;
import java.util.*;
import java.net.*;
import java.io.*;
import java.util.*;
public class ChatHandler extends Thread {
protected Socket s;
protected DataInputStream i;
protected DataOutputStream o;
public ChatHandler (Socket s) throws IOException {
this.s = s;
i = new DataInputStream (new BufferedInputStream (s.getInputStream ()));
o = new DataOutputStream (new BufferedOutputStream (s.getOutputStream ()));
}
protected static Vector handlers = new Vector ();
p ublic void run () {
String name = s.getInetAddress ().toString ();
try {
broadcast (name + " has joined.");
handlers.addElement (this);
while (true) {
String msg = i.readUTF ();
broadcast (name + " - " + msg);
}
} catch (IOException ex) {
ex.printStackTrace ();
} finally {
handlers.removeElement (this);
broadcast (name + " has left.");
try {
s.close ();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
protected static void broadcast (String message) {
synchronized (handlers) {
Enumeration e = handlers.elements ();
while (e.hasMoreElements ()) {
ChatHandler c = (ChatHandler) e.nextElement ();
try {
synchronized (c.o) {
c.o.writeUTF (message);
}
c.o.flush ();
} catch (IOException ex) {
c.stop ();
}
}
}
}
2. Cliente de chat
El programa cliente se ha implementado tanto en forma de aplicación como en forma de
applet. Como se puede observar, en general, la mayor parte del código es similar.
/**
* ChatClient.java 1.00 98/10/05 Humberto MartÌnez Barber·
*
* Basado en ChatApplet de Merlin Hughes
*/
import java.net.*;
import java.io.*;
import java.awt.*;
public class ChatClient extends Frame implements Runnable {
protected DataInputStream i;
protected DataOutputStream o;
protected TextArea output;
protected TextField input;
protected Thread listener;
public ChatClient (String title, InputStream i, OutputStream o) {
super (title);
this.i = new DataInputStream (new BufferedInputStream (i));
this.o = new DataOutputStream (new BufferedOutputStream (o));
setLayout (new BorderLayout ());
add ("Center", output = new TextArea ());
output.setEditable (false);
add ("South", input = new TextField ());
pack ();
show ();
input.requestFocus ();
listener = new Thread (this);
listener.start ();
}
public void run () {
try {
while (true) {
String line = i.readUTF ();
output.appendText (line + "\n");
}
} catch (IOException ex) {
ex.printStackTrace ();
} finally {
listener = null;
input.hide ();
validate ();
try {
o.close ();
} catch (IOException ex) {
ex.printStackTrace ();
}
}
}
public boolean handleEvent (Event e) {
if ((e.target == input) && (e.id == Event.ACTION_EVENT)) {
try {
o.writeUTF ((String) e.arg);
o.flush ();
} catch (IOException ex) {
ex.printStackTrace();
listener.stop ();
}
input.setText ("");
return true;
} else if ((e.target == this) && (e.id == Event.WINDOW_DESTROY)) {
if (listener != null)
listener.stop ();
hide ();
return true;
}
return super.handleEvent (e);
}
public static void main (String args[]) throws IOException {
if (args.length != 2)
throw new RuntimeException ("Syntax: ChatClient ");
Socket s = new Socket (args[0], Integer.parseInt (args[1]));
new ChatClient ("Chat " + args[0] + ":" + args[1],
s.getInputStream (), s.getOutputStream ());
}
/**
* ChatApplet.java 1.00 96/11/01 Merlin Hughes
*
* Copyright (c) 1996 Prominence Dot Com, Inc. All Rights Reserved.
*
* Permission to use, copy, modify, and distribute this software
* for non-commercial purposes and without fee is hereby granted
* provided that this copyright notice appears in all copies.
*
* http://prominence.com/ merlin[arroba]prominence.com
*/
import java.net.*;
import java.io.*;
import java.awt.*;
import java.applet.*;
// Applet parameters:
// host = host name
// port = host port
public class ChatApplet extends Applet implements Runnable {
protected DataInputStream i;
protected DataOutputStream o;
protected TextArea output;
protected TextField input;
protected Thread listener;
public void init () {
setLayout (new BorderLayout ());
add ("Center", output = new TextArea ());
output.setEditable (false);
add ("South", input = new TextField ());
input.setEditable (false);
}
public void start () {
listener = new Thread (this);
listener.start ();
}
public void stop () {
if (listener != null)
listener.stop ();
listener = null;
}
public void run () {
try {
String host = getParameter ("host");
if (host == null)
host = getCodeBase ().getHost ();
String port = getParameter ("port");
if (port == null)
port = "9830";
output.appendText ("Connecting to " + host + ":" + port + "...");
Socket s = new Socket (host, Integer.parseInt (port));
i = new DataInputStream (new BufferedInputStream (s.getInputStream ()));
o = new DataOutputStream (new BufferedOutputStream (s.getOutputStream ()));
output.appendText (" connected.\n");
input.setEditable (true);
input.requestFocus ();
execute ();
} catch (IOException ex) {
ByteArrayOutputStream out = new ByteArrayOutputStream ();
ex.printStackTrace (new PrintStream (out));
output.appendText ("\n" + out);
}
}
public void execute () {
try {
while (true) {
String line = i.readUTF ();
output.appendText (line + "\n");
}
} catch (IOException ex) {
ByteArrayOutputStream out = new ByteArrayOutputStream ();
ex.printStackTrace (new PrintStream (out));
output.appendText (out.toString ());
} finally {
listener = null;
input.hide ();
validate ();
try {
o.close ();
} catch (IOException ex) {
ex.printStackTrace ();
}
}
}
public boolean handleEvent (Event e) {
if ((e.target == input) && (e.id == Event.ACTION_EVENT)) {
try {
o.writeUTF ((String) e.arg);
o.flush ();
} catch (IOException ex) {
ex.printStackTrace();
listener.stop ();
}
input.setText ("");
return true;
} else if ((e.target == this) && (e.id == Event.WINDOW_DESTROY)) {
if (listener != null)
listener.stop ();
hide ();
return true;
}
return super.handleEvent (e);
}
}
make a chat room for your web page.
Making an xat.com chat box is easy and completely free. Just choose a background and
size, press the Update button and copy and paste the code from the box below into your
web page, MySpace or blog. MySpace users click here. Facebook users click here. To make
a chat group click here.
Principio del formulario
New chat 0 1 http://w w w .xat.c
http://myinfochat.eliveengine.com/myinfo
chat/servlet/infolet.InfoServlet
<!--$#-- begin secure instant messaging chat server software
http://www.12planet.com YOU SHOULD NOT MODIFY THE HTML CODE EXCEPT
FOR THE APPLET PARAMETERS-------------->
<center>
var chatskinID ="mac"; //select the skin "mac" (supported values are basic,
future, mac, organizer, palm, skycloud, skynight), should set chatskin="skin"
first
var chatskinPopupH = "405"; //for the skin mode only, private chat popup
height
var chatskinPopupW = "367"; //for the skin mode only, private chat popup
width
</script>
<script language="JavaScript"
SRC="http://www.myinfochat.com/myinfochat/profile/myinfochat_top.js"></scr
ipt>
</APPLET>
<br>
</a>
</font>
<br>
<br>
<script language=javascript>
function doJoin(a,b)
top.frames.infochatapplet.document.applets.chatapplet.doJoin(a,b);
function openwindow(page,target,a_width,a_height)
{ window.open(page,target,'toolbar=no,location=no,directories=no,status=no,
menubar=no,resizable=yes,copyhistory=no,scrollbars=yes,width=a_width,hei
ght=a_height');
function BtSave()
myWindow = window.open('','displayWindow');
myWindow.document.write(" <br>");
myWindow.document.write(" <br>");
myWindow.document.write(" <br>");
myWindow.document.write(" <br>");
myWindow.document.write(document.applets.chatapplet.getChatLog());
</script>
<form>
</form>
</center>
86
i
6 Votes
Ventana cliente
Ventana Privado
(Editado Marzo del 2009) Agradecería a las personas que han mejorado este
proyecto y/o modificado enviarlo a mi correo electronico: valsrock@gmail.com .
Espero sus mails .Salu2
1. Se inicia el servidor
2. El servidor se mantiene escuchando cualquier petición de un cliente para
conectarse.
3. El servidor acepta al cliente.
4. El servidor lanza un hilo de comunicación con el cliente.
5. Por el hilo se envían y reciben mensajes a través del servidor entre todos
los clientes.
6. Si el cliente cierra la comunicación el hilo se rompe y se corta la
comunicación con ese cliente.
La implementación del programa cliente sigue las siguientes ideas:
1. Se inicia el cliente
2. El cliente lanza una petición al servidor para conectarse
3. El servidor asigna un hilo al cliente al ser aceptado.
4. El cliente envía y recibe mensajes por el hilo hacia todos o hacia algun
usuario específico, usando al servidor como puente para las
comunicaciones.
Para esto se ha empleado objetos de la clase ServerSocket y Socket para el
servidor y cliente respectivamente que permiten la conexion entre cliente y
servidor mientras que los Hilos sirven para hacer que el servidor se mantenga
escuchando y no interrumpa su proceso mientras los clientes se comunican a
traves de mensajes.A continuacion unas definiciones:
Sockets:Los sockets no son más que puntos o mecanismos de comunicación
entre procesos que permiten que un proceso hable ( emita o reciba
información ) con otro proceso incluso estando estos procesos en distintas
máquinas. Esta característica de interconectividad entre máquinas hace que el
concepto de socket nos sirva de gran utilidad.