Uso de Sockets y Threads en aplicaciones Cliente-Servidor en Java

Aquí les traigo un código de una sencilla aplicación cliente-servidor hecho en Java.

La aplicación maneja la comunicación por sockets y usa multihilos (threads) igual de forma remota. Aunque el programa en sí no tiene un uso muy práctico en la realidad, les puede dar una base de lo que es la comunicación por sockets y el uso de los threads.

La aplicación consta del programa cliente y el programa servidor. El servidor recibe las ordenes del cliente para ejecutar movimientos de 2 figuras en 4 direcciones
Se necesita depurar el servidor primero para que funcione, y el cliente tiene que compilarse y luego depurar el applet.

Éste es el código del servidor:

import java.io.*;
import java.applet.Applet;
import java.awt.*;
import java.net.*;
public class Servidor extends Frame
{
int x=180,y=300,i;
int m=180,n=360,s;
boolean flag=false;
Button b1,b2,b3,b4,b5,b6,b7,b8;
TextArea area;
ServerSocket serverSocket=null;
Socket clientSocket=null;
PrintWriter out;
BufferedReader in;
String entrada;
Receive R;
public Servidor()
{
super(“Servidor para uso de Sockets y Threads”);
setLayout(new FlowLayout());
add(area=new TextArea(15,35));
resize(400,450);
show();
repaint();
connect();
R=new Receive();
R.start();
}
public void connect()
{
showText(“Estado: Conectando…”);
try
{
serverSocket = new ServerSocket(80);
clientSocket = serverSocket.accept();
out = new PrintWriter(clientSocket.getOutputStream(),true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
}
catch(Exception e)
{
if (flag=false)
{
showError(e.toString());showError(e.toString());
}
flag=true;
}
showText(“Estado: Conectado”);
}
public void disconnect()
{
showText(“Estado: Desconectando…”);
try
{
out.close();
in.close();
clientSocket.close();
serverSocket.close();
flag=false;
}
catch(Exception e)
{
if (flag=false)
{
showError(e.toString());
}
flag=true;
}
showText(“Estado: Desconectado”);
}
public void showError(String S)
{
area.appendText(“Estado: Desconectado…”+”\n”+”Vuelva a cargar el cliente y el servidor…”+”\n”);
}
public void showText(String S)
{
area.appendText(S+”\n”);
}
public class Receive extends Thread
{
public void run()
{
while (true)
{
try
{
if ((entrada = in.readLine())!=null);
{
showText(entrada);
if (entrada.equals(“Cuadro arriba”))
n=n-30;
if (entrada.equals(“Círculo arriba”))
y=y-30;
if (entrada.equals(“Cuadro abajo”))
n=n+30;
if (entrada.equals(“Círculo abajo”))
y=y+30;
if (entrada.equals(“Cuadro izquierda”))
m=m-30;
if (entrada.equals(“Círculo izquierda”))
x=x-30;
if (entrada.equals(“Cuadro derecha”))
m=m+30;
if (entrada.equals(“Círculo derecha”))
x=x+30;
if (entrada.equals(“Adiós!!!”))
break;
repaint();
}
}
catch(Exception e)
{
showError(e.toString());
}
}
}
}
public void send(String a)
{
out.println(a);
showText(“Local: “+a);
}
public void paint( Graphics g ) {
g.setColor(Color.red);
g.fillOval(x,y,50,50);
g.setColor(Color.blue);
g.fillRect(m,n,50,50);
}
public static void main (String args [])
{
new Servidor();
}
}

Y el código del cliente:Descarga la aplicación

Espero que sea de utilidad para alguien.

KobraSoft®

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>