WCFHelper

Posted by Jack Daliss | 20:04 Categories:
JOBS

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BbWcfHelper
{
    public class Jobs
    {
        #region declaraciones tramas por segundo

            static OperationsDB operacionesdb= new OperationsDB();
            Methods methods = new Methods();
            List<DataTable> lista = new List<DataTable>();
            DataTable dt_retorno = new DataTable();
            DataSet ds_retorno = new DataSet();
            static int Id_componente;
            static string Hora_inicio;
            static string Fecha;
            static string Hora_fin;
            static int Tipo_tramsaccion;
            static int Tramas;
            public static int Posicion_actual_lista = 0;
           
        #endregion

        #region metodos trama por segundo

            public Jobs(int id_componente, string fecha, string hora_inicio, string hora_fin, int tipo_tramsaccion, int tramas)
            {
                Id_componente = id_componente;
                Fecha = fecha;
                Hora_inicio = hora_inicio;
                Hora_fin = hora_fin;
                Tipo_tramsaccion = tipo_tramsaccion;
                Tramas = tramas;
            }

            public Jobs()
            { }

            public void procesa_cargas_tramas_por_segundo(int cantidad_tramas)
            {
                lock (this)
                {
                    operacionesdb.CopiarTramasATramasEnvioTemp(Id_componente, Fecha, Hora_inicio, Hora_fin, Tipo_tramsaccion, Tramas);
                    if (methods.contar_paquetes_disponibles(ref lista) <= 2)
                    {
                        methods.llena_lista_tramas_por_segundo(ref lista,cantidad_tramas);
                    }
                    else if (methods.contar_paquetes_null(ref lista) > 5)//6000)
                    {
                        methods.remueve_null_lista(ref lista);
                    }
                }
            }

            public DataSet retorna_paquete_Trams_Seg(int cantidad_tramas)
            {
                ds_retorno.Tables.Clear();  
                dt_retorno.Rows.Clear();
                dt_retorno = lista[Posicion_actual_lista].Copy();
                ds_retorno.Tables.Add(dt_retorno);
                lista[Posicion_actual_lista] = null;
                Posicion_actual_lista++;
                Task tarea = new Task(() => procesa_cargas_tramas_por_segundo(cantidad_tramas));
                tarea.Start();
                return ds_retorno;
            }

            public void procesa_cargas_simulacion_dia()
            {
                lock (this)
                {
                    operacionesdb.CopiarTramasATramasEnvioTemp(Id_componente, Fecha, Hora_inicio, Hora_fin, Tipo_tramsaccion, Tramas);

                    if (methods.contar_paquetes_disponibles(ref lista) <= 120)
                    {
                        methods.llena_lista_simulacion_dia(ref lista);
                    }
                    else if (methods.contar_paquetes_null(ref lista) > 1000)//6000)
                    {
                        methods.remueve_null_lista(ref lista);
                    }
                }
            }

            public DataSet retorna_paquete_Sim_Dia()
            {
                DataSet ds_temp = new DataSet();

                int limite = Posicion_actual_lista;

                for (int i = Posicion_actual_lista; i < limite + 60; i++)
                {
                    ds_temp.Tables.Add(lista[i]);

                    Posicion_actual_lista++;
                    lista[i] = null;
                }

                Task tarea = new Task(() => procesa_cargas_simulacion_dia());
                tarea.Start();
                return ds_temp;
            }

        #endregion


    }
}


XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

METHODS

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BbWcfHelper
{
    class Methods
    {
        OperationsDB operationsdb = new OperationsDB();
        DataTable dt_segundos;

        //Metodo que llena la lista de tabla de tramas cada cierto tiempo
        public void llena_lista_tramas_por_segundo(ref List<DataTable> lista,int cantidad_tramas )
        {
            DataTable dt_consulta = new DataTable();
            DataTable dt_nueva = new DataTable();

            for (int c = 0; c < 4; c++)
            {
                dt_consulta = operationsdb.ConsultaTramasEnvioTemp(cantidad_tramas);
                dt_nueva = dt_consulta.Clone();
                dt_nueva = dt_consulta;
                if (dt_consulta.Rows.Count > 0)
                {
                    lista.Add(dt_nueva);
                    dt_nueva.Dispose();
                    dt_nueva = new DataTable();
                    dt_nueva = dt_consulta.Clone();
                }
            }
            dt_consulta.Dispose();
            dt_nueva.Dispose();
        }

        public int contar_paquetes_disponibles(ref List<DataTable> lista)
        {
            int cont = 0;
            for (int i = 0; i < lista.Count; i++)
            {
                cont = (lista[i] != null) ? cont += 1 : cont;
            }
            return cont;
        }

        public int contar_paquetes_null(ref List<DataTable> lista)
        {
            int cont = 0;
            for (int i = 0; i < lista.Count; i++)
            {
                cont = (lista[i] == null) ? cont += 1 : cont;
            }
            return cont;
        }

        public void llena_lista_simulacion_dia(ref List<DataTable> lista)
        {
            DataTable dt_consulta = new DataTable();
            DataRow row;

            dt_consulta = operationsdb.ConsultaTramasEnvioTemp(2000);

            dt_segundos = dt_consulta.Clone();

            //verifica que la consulta contenga datos
            if (dt_consulta.Rows.Count > 0)
            {
                string segundos = dt_consulta.Rows[0]["hora_envio_log"].ToString();

                //recorre la tabla minuto, que se consulto
                for (int i = 0; i <= dt_consulta.Rows.Count; i++)
                {
                    if (i < dt_consulta.Rows.Count)
                        if (segundos == dt_consulta.Rows[i]["hora_envio_log"].ToString())
                        {
                            row = dt_segundos.NewRow();
                            row[0] = dt_consulta.Rows[i]["id"].ToString();
                            row[1] = dt_consulta.Rows[i]["trama"].ToString();
                            row[2] = dt_consulta.Rows[i]["hora_envio_log"].ToString();
                            row[3] = dt_consulta.Rows[i]["id_componente"].ToString();
                            dt_segundos.Rows.Add(row);
                        }
                        else
                        {
                            segundos = dt_consulta.Rows[i]["hora_envio_log"].ToString();
                            lista.Add(dt_segundos);
                            dt_segundos.Dispose();
                            crea_estructura_tabla();
                            i--;
                        }
                    else
                    {
                        lista.Add(dt_segundos);
                        dt_segundos.Dispose();
                        crea_estructura_tabla();
                    }
                }
                dt_consulta.Rows.Clear();
            }
            else
            {
                //no se encontro datos
            }
            dt_consulta.Dispose();
        }

        public void crea_estructura_tabla()
        {
            dt_segundos = new DataTable();
            dt_segundos.Columns.Add("id");
            dt_segundos.Columns.Add("trama");
            dt_segundos.Columns.Add("hora");
            dt_segundos.Columns.Add("id_componente");
        }

        public void remueve_null_lista(ref List<DataTable> lista)
        {
            for (int i = 0; i < lista.Count;i++ )
            {
                if (lista[i] == null)
                {
                    lista.RemoveAt(i);
                    i--;
                }
            }

                Jobs.Posicion_actual_lista = 0;
        }

    }




}






    
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

OPERATIONDB

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BbWcfHelper
{
    public class OperationsDB
    {
        //copia las tablas a la tramas envío temporal
        public void CopiarTramasATramasEnvioTemp(int id_componente, string fecha, string hora_inicio, string hora_fin, int tipo_tramsaccion, int tramas)
        {
            //GeneralConnection.Conexion conexion = new GeneralConnection.Conexion(ConfigurationManager.AppSettings["conexiondb"]);

            //try
            //{
            //    SqlCommand com = new SqlCommand("SPBGCopiaTramasATramasEnvioTempOrg", conexion.iniciar());
            //    com.Parameters.AddWithValue("@componente", id_componente);
            //    com.Parameters.AddWithValue("@fecha_simular", fecha);
            //    com.Parameters.AddWithValue("@hora_inicio", hora_inicio);
            //    com.Parameters.AddWithValue("@hora_fin", hora_fin);
            //    com.Parameters.AddWithValue("@tipo_transaccion", tipo_tramsaccion);
            //    com.Parameters.AddWithValue("@tramas", tramas);
            //    com.CommandType = CommandType.StoredProcedure;
            //    com.ExecuteNonQuery();

            //}
            //catch (Exception ex)
            //{

            //}
            //finally
            //{
            //    conexion.cerrar_conexion();
            //}



            GeneralConnection.Conexion conexion = new GeneralConnection.Conexion(ConfigurationManager.AppSettings["conexiondb"]);

            try
            {
                SqlCommand com = new SqlCommand("copia", conexion.iniciar());
                com.Parameters.AddWithValue("@cant", 9000);
                com.CommandType = CommandType.StoredProcedure;
                com.ExecuteNonQuery();
            }
            catch (Exception ex)
            {

            }
            finally
            {
                conexion.cerrar_conexion();
            }
        }

        //Método que realiza la consulta de ciertas tramas, para procesarlas por segundos además las tramas que trae las marca como enviadas='E'
        public DataTable ConsultaTramasEnvioTemp(int Tramas)
        {
            //GeneralConnection.Conexion conexion = new GeneralConnection.Conexion(ConfigurationManager.AppSettings["conexiondb"]);
            //DataSet ds = new DataSet();

            //try
            //{
            //    SqlCommand com = new SqlCommand("SPBGConsultaTramasEnvioTempOrg", conexion.iniciar());
            //    com.Parameters.AddWithValue("@Tramas", Tramas);
            //    com.CommandType = CommandType.StoredProcedure;
            //    SqlDataAdapter adaptador = new SqlDataAdapter(com);
            //    adaptador.Fill(ds);
            //}
            //catch (Exception ex)
            //{

            //}
            //finally
            //{
            //    conexion.cerrar_conexion();
            //}
            //return ds.Tables[0];


            GeneralConnection.Conexion conexion = new GeneralConnection.Conexion(ConfigurationManager.AppSettings["conexiondb"]);
            DataSet ds = new DataSet();

            try
            {
                SqlCommand com = new SqlCommand("consulta", conexion.iniciar());
                com.Parameters.AddWithValue("@cant", Tramas);
                com.CommandType = CommandType.StoredProcedure;
                SqlDataAdapter adaptador = new SqlDataAdapter(com);
                adaptador.Fill(ds);
            }
            catch (Exception ex)
            {

            }
            finally
            {
                conexion.cerrar_conexion();
            }
            return ds.Tables[0];


            //DataTable dt = new DataTable();
            //dt.Columns.Add("columna1");
            //for (int i = 0; i < 200; i++)
            //{
            //    DataRow dr = dt.NewRow();
            //    dr[0] = "holatttt:" + i.ToString();
            //    dt.Rows.Add(dr);
            //}



            //DataTable dt = new DataTable();
            //dt.Columns.Add("id");
            //dt.Columns.Add("trama");
            //dt.Columns.Add("hora_envio_log");
            //dt.Columns.Add("id_componente");

            //for (int i = 0; i < 3000; i++)
            //{



            //    DataRow dr = dt.NewRow();
            //    dr[0] = "holatttt:" + i.ToString();
            //    dr[1] = "fffffff:" + i.ToString();
            //    if (i < 1500)
            //    {
            //        dr[2] = "00:00:01" + i.ToString();
            //    }
            //    else
            //    {
            //        dr[2] = "00:00:02" + i.ToString();
            //    }
            //    dr[3] = "hhhh:" + i.ToString();
            //    dt.Rows.Add(dr);
            //}

            //return dt;
        }

    }
}



XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX


HELPER SERVICE


using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using BbWcfHelper;
using System.Data;

namespace WCFHelper
{
    
    public class HelperService : IHelperService
    {
        static Jobs jobs; 

        public bool Iniciar_Proceso_Consulta_Trams_Seg(int id_componente, string fecha, string hora_inicio, string hora_fin, int tipo_tramsaccion, int tramas)
        {
            jobs = new Jobs(id_componente, fecha, hora_inicio, hora_fin, tipo_tramsaccion, tramas);
            OperationsDB operacionesdb = new OperationsDB();
            operacionesdb.CopiarTramasATramasEnvioTemp(id_componente, fecha, hora_inicio, hora_fin, tipo_tramsaccion, tramas);
            jobs.procesa_cargas_tramas_por_segundo(200);
            return true;
        }

        public DataSet Obtener_Paquete_Trams_Seg(int cantidad_tramas)
        {
            return jobs.retorna_paquete_Trams_Seg(cantidad_tramas);
        }

        public bool Iniciar_Proceso_Consulta_Sim_Dia(int id_componente, string fecha, string hora_inicio, string hora_fin, int tipo_tramsaccion, int tramas)
        {
            jobs = new Jobs(id_componente, fecha, hora_inicio, hora_fin, tipo_tramsaccion, tramas);
            OperationsDB operacionesdb = new OperationsDB();
            operacionesdb.CopiarTramasATramasEnvioTemp(id_componente, fecha, hora_inicio, hora_fin, tipo_tramsaccion, tramas);
            jobs.procesa_cargas_simulacion_dia();
            return true;


        }

        public DataSet Obtener_Paquete_Sim_Dia()
        {
            return jobs.retorna_paquete_Sim_Dia();
        }



    }
}



XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

IHELPER SERVICE

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace WCFHelper
{
    
    [ServiceContract]
    public interface IHelperService
    {
        [OperationContract]
        bool Iniciar_Proceso_Consulta_Trams_Seg(int id_componente, string fecha, string hora_inicio, string hora_fin, int tipo_tramsaccion, int tramas);

        [OperationContract]
        DataSet Obtener_Paquete_Trams_Seg(int cantidad_tramas);

        [OperationContract]
        bool Iniciar_Proceso_Consulta_Sim_Dia(int id_componente, string fecha, string hora_inicio, string hora_fin, int tipo_tramsaccion, int tramas);

        [OperationContract]
        DataSet Obtener_Paquete_Sim_Dia();

    }
}



Blogger news

Comments

Not using Html Comment Box  yet?
JACK · Sept 16, 2017

XXXXXXXXX ESTE ES EL CODIGO DE LA CLASE SERPIENTE XXXXX




import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

class Serpiente extends JFrame implements KeyListener, Runnable {

JPanel p1, p2;
JButton[] lb = new JButton[200];
JButton regalo;
JTextArea t;
int x = 500,
y = 250,
tamaño_inicial = 2,
direccion = 1,
direccionamiento = 0,
velocidad = 50,
diferencia = 0,
oldx,
oldy,
puntos = 0;

int[] lbx = new int[300];
int[] lby = new int[300];
Point[] lbp = new Point[300];
Point bfp = new Point();
Thread myt;
boolean comida = false,
_runl = false,
_runr = true,
_runu = true,
_rund = true,
bonificacion = true;

Random r = new Random();
JMenuBar mi_menu;
JMenu juego, ayuda, nivel;


public void InicializarValores() {
tamaño_inicial = 3;
lbx[0] = 100;
lby[0] = 150;
direccion = 10;
direccionamiento = 0;
diferencia = 0;
puntos = 0;
comida = false;
_runl = false;
_runr = true;
_runu = true;
_rund = true;
bonificacion = true;
}

Serpiente() {
super("Juego de la Serpiente");
setSize(500, 330);
CrearMenu();
InicializarValores();
p1 = new JPanel();
p2 = new JPanel();
t = new JTextArea("Puntos: " + puntos);
t.setEnabled(false);
t.setBackground(Color.WHITE);
regalo = new JButton();
regalo.setEnabled(false);
CrearPrimeraSerpiente();

p1.setLayout(null);
p2.setLayout(new GridLayout(0, 1));
p1.setBounds(0, 0, x, y);
p1.setBackground(Color.BLACK);
p2.setBounds(0, y, x, 30);
p2.setBackground(Color.RED);

p2.add(t);
getContentPane().setLayout(null);
getContentPane().add(p1);
getContentPane().add(p2);

setDefaultCloseOperation(EXIT_ON_CLOSE);

addKeyListener(this);
myt = new Thread(this);
myt.start();
}

public void CrearPrimeraSerpiente() {
for (int i = 0; i < 3; i++) {
lb[i] = new jbutton("lb" + i);
lb[i].setenabled(false);
p1.add(lb[i]);
lb[i].setbounds(lbx[i],lby[i], 10, 10);
lbx[i + 1] = lbx[i] - 10;
lby[i + 1] = lby[i];
}
}

public void crearmenu() {
mi_menu = new jmenubar();

juego = new jmenu("juego");

jmenuitem newgame = new jmenuitem("iniciar nuevamente");
jmenuitem exit = new jmenuitem("salir");

newgame.addactionlistener(
new actionlistener() {

public void actionperformed(actionevent e) {
reiniciar();
}
});

exit.addactionlistener(new actionlistener() {

public void actionperformed(actionevent e) {
system.exit(0);
}
});

juego.add(newgame);
juego.addseparator();
juego.add(exit);

mi_menu.add(juego);


jmenuitem creator = new jmenuitem("creador de juego");


creator.addactionlistener(new actionlistener() {

public void actionperformed(actionevent e) {
joptionpane.showmessagedialog(p2, "nombre : ");
}
});

setjmenubar(mi_menu);
}

void reiniciar() {
inicializarvalores();
p1.removeall();

myt.stop();

crearprimeraserpiente();
t.settext("puntos: " + puntos);

myt = new thread(this);
myt.start();
}

void hacermasgrande() {
lb[tamaño_inicial] = new jbutton();
lb[tamaño_inicial].setenabled(false);
p1.add(lb[tamaño_inicial]);
int a = 10 + (10 * r.nextint(48));
int b = 10 + (10 * r.nextint(23));
system.out.print("\nx"+a);
system.out.print("\ny"+b);
lbx[tamaño_inicial] = a;
lby[tamaño_inicial] = b;
lb[tamaño_inicial].setbounds(a, b, 10, 10);

tamaño_inicial++;
}
void moveradelante() {
for (int i = 0; i < tamaño_inicial; i++) {
lbp[i] = lb[i].getlocation();

system.out.print("\nlbp i=0 1<3 i++"+lbp[i]);
system.out.print("\nlb "+lb[i]);
}

lbx[0] += direccion;
system.out.print("\nlbx"+lbx[0]);
lby[0] += direccionamiento;
system.out.print("\nlby"+lby[0]);
lb[0].setbounds(lbx[0], lby[0], 10, 10);

for (int i = 1; i < tamaño_inicial; i++) {
lb[i].setlocation(lbp[i-1 ]);
system.out.print("\nlb 1<3 i++ i-1"+lb[i]);
}

if (lbx[0] == x) {
lbx[0] = 10;

} else if (lbx[0] == 0) {
lbx[0] = x - 10;

} else if (lby[0] == y) {
lby[0] = 10;

} else if (lby[0] == 0) {
lby[0] = y - 10;
}

if (lbx[0] == lbx[tamaño_inicial - 1] && lby[0] == lby[tamaño_inicial - 1]) {
comida = false;
puntos += 5;
t.settext("puntos: " + puntos);
if (puntos % 50 == 0 && bonificacion == true) {
p1.add(regalo);
regalo.setbounds((10 * r.nextint(50)), (10 * r.nextint(25)), 15, 15);
bfp = regalo.getlocation();
bonificacion = false;
}
}

if (bonificacion == false) {
if (bfp.x <= lbx[0] && bfp.y <= lby[0] && bfp.x + 10 >= lbx[0] && bfp.y + 10 >= lby[0]) {
p1.remove(regalo);
puntos += 100;
t.setText("Puntos: " + puntos);
bonificacion = true;
}
}

if (comida == false) {
HacerMasGrande();
comida = true;
} else {
lb[tamaño_inicial - 1].setBounds(lbx[tamaño_inicial - 1], lby[tamaño_inicial - 1], 10, 10);
}

for (int i = 1; i < tamaño_inicial; i++) {
if (lbp[0] == lbp[i]) {
t.settext("hoooo! perdiste :( " + puntos);
try {
myt.join();
} catch (interruptedexception ie) {
}
break;
}
}


p1.repaint();
show();
}

public void keypressed(keyevent e) {
if (_runl == true && e.getkeycode() == 37) {
direccion = -10;
direccionamiento = 0;
_runr = false;
_runu = true;
_rund = true;
}
if (_runu == true && e.getkeycode() == 38) {
direccion = 0;
direccionamiento = -10;
_rund = false;
_runr = true;
_runl = true;
}
if (_runr == true && e.getkeycode() == 39) {
direccion = +10;
direccionamiento = 0;
_runl = false;
_runu = true;
_rund = true;
}
if (_rund == true && e.getkeycode() == 40) {
direccion = 0;
direccionamiento = +10;
_runu = false;
_runr = true;
_runl = true;
}
}

public void keyreleased(keyevent e) {
}

public void keytyped(keyevent e) {
}

public void run() {
for (;;) {

moveradelante();
try {
thread.sleep(velocidad);
} catch (interruptedexception ie) {
}
}
}

}



xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx>

Jack · Sept 16, 2017

XXXXXXXX AQUI ESTA EL CODIGO DEL MAIN XXXXXX

public class main {

public static void main(String[] args) {
// TODO Auto-generated method stub
new Serpiente();
}

}


XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

TCP/IP · Sept 21, 2015

Tcp/IP Sockets C#
Una red de computadoras (ordenadores) consiste en máquinas interconectadas mediante canales de comunicación. Estas máquinas son Hosts y Routers. Los Hosts son computadoras que ejecutan aplicaciones, por ejemplo un navegador. Los Routers son equipos cuyo trabajo es retransmitir información de un canal de comunicación a otro. Estos pueden ejecutar programas, pero normalmente no son aplicativos. Para este post un canal de comunicación es un medio de transmisión de secuencias de bytes de un host a otro, este puede ser broadcast, como Ethernet, un modem dial-up, o algo más sofisticado.

Otro término que tenemos que definir es Protocolo. Un protocolo es un acuerdo acerca de los paquetes intercambiados por comunicación de los programas y lo que significan, además describe como está estructurado, por ejemplo: donde está la información del destinatario en el paquete y de que tamaño es. Un ejemplo es Http (Hypertext Transfer Protocol) que resuelve el problema de transferir objectos hipertexto entre servidores y hacerlo entendible por personas.

Ahora vamos directo al grano: ¿Qué es un Socket?

Un socket es una abstracción que permite a la aplicación “enchufarse” a la red para poder recibir y enviar data. Los principales tipos de socket hoy en día son los Stream Socket y los Datagram Socket. Los Stream Sockets utilizan TCP e IP para proveer n servicio confiable. Los Datagram Sockets usan UDP.

Otro concepto importante son el Stream Reader y el Stream Writer.

Son clases que nos ayudan a escribir y leer del buffer del socket. Sino existieran habría que leer el buffer y escribir en él directamente, cosa que es un poco engorrosa e innecesaria para la mayoría de las aplicaciones.

Código de ejemplo:



public class NetworkServer
{
public static void Main()
{
//creamos un thread para que el server
//se ejecute en paralelo con el cliente
//esto es solo por motivos prácticos del demo
new Thread(new ThreadStart(
delegate {
new NetworkServer().Start(); }
)).Start();

//Iniciamos el Cliente
new Client().Connect();
Console.WriteLine("Listo");
Console.Read();

}

public void Start()
{
// Creamos un TcpListener y le indicamos que
//puerto va a poner en escucha.
TcpListener tcpListener = new TcpListener(9898);

//Iniciamos la esucha
tcpListener.Start();

//Este método queda bloqueado hasta que
//se conecte un cliente
Socket socketForClient = tcpListener.AcceptSocket();

if (socketForClient.Connected)
{
// Si se conecta
Console.WriteLine("Cliente conectado.");
//Creamos el networkSream, el Reader y el writer
NetworkStream networkStream =
new NetworkStream(socketForClient);

StreamWriter streamWriter =
new StreamWriter(networkStream);

StreamReader streamReader =
new StreamReader(networkStream);

//Esta es la data a enviar.
string theString = "Esta es la data de envio";

try
{
//Escribimos la data en el stream
streamWriter.WriteLine(theString);
//Ahora le decimos que la mande.
streamWriter.Flush();
//Esperamos data del cliente
//Y la escribimos por consola.
theString = streamReader.ReadLine();

Console.WriteLine(theString);
}
finally
{
//Cerramos las conexiones
streamReader.Close();
streamWriter.Close();
networkStream.Close();
socketForClient.Close();
}
}
}
}



public class Client
{
public void Connect()
{
TcpClient socketForServer;
string server = "localhost";
try
{
//Creamos

rss
  • RSS
  • Delicious
  • Digg
  • Facebook
  • Twitter
  • Linkedin
  • Youtube