Exemplo em TCP/IP ajuda...

04/12/2007

0

[b:3a49126811]Este codigo abaixo esta funcionado, ok!
mas tem somente um probleminha so aceita um cliente...
nao estou conseguindo entrar uma forma de fazer com que aceite mas de uma [/b:3a49126811]

[b:3a49126811]SE ALGUEM PODER AJUDAR FICO GRATO![/b:3a49126811]

[u:3a49126811][i:3a49126811][b:3a49126811]Server[/b:3a49126811][/i:3a49126811][/u:3a49126811]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
// Acesso 
using System.Threading;
using System.Net.Sockets;
using System.IO;


namespace Server
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private delegate void DelegateControleDisplay(string texto);
        private Socket connection;
        private Thread readThread;
        private NetworkStream socketStream;
        BinaryWriter writer;
        BinaryReader reader;

        private void btnStart_Click(object sender, EventArgs e)
        {
            readThread = new Thread(new ThreadStart(RunServer));
            readThread.Start();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            System.Environment.Exit(System.Environment.ExitCode);
        }

        private void Input_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Enter && connection != null)
                {
                    if (Input.Text.ToUpper() == "FIM")
                    {
                        connection.Close();
                    }
                }
            }
            catch (SocketException se)
            {
                Display.Text += "Erro: " + se;
            }
        }


        public void RunServer()
        {
            TcpListener listener;
            int counter = 1;
            // espera por uma conexao de cliente 
            try
            {
                listener = new TcpListener(5000);
                listener.Start();
                while (true)
                {
                    PegaControlePorThread("esperando po conexoes...");
                    // aceita conexoes recebidas
                    connection = listener.AcceptSocket();
                    // cria objetos NetWorkStream
                    socketStream = new NetworkStream(connection);
                    // cria objetos para transmitir dados por fluxo
                    writer = new BinaryWriter(socketStream);
                    reader = new BinaryReader(socketStream);

                   PegaControlePorThread(counter + " Conexoes recebidas.");

                    // responde ao cliente que a conexao foi aceita
                    writer.Write("Conexao aceita");
                    Input.ReadOnly = false;

                    string theReply = "";
                    //le dados da string enviada do cliente
                    do
                    {
                        try
                        {
                           //  le atring enviada para o servidor
                             theReply = reader.ReadString();
                          //   exibe a mensagem
                            PegaControlePorThread("\n" + theReply);
                        }
                        // manipula a execução, se houver erro ao ler os dados
                        catch (Exception)
                        {
                            break;                            
                        }                        
                    } while (theReply.ToUpper() != "FIM");

                   PegaControlePorThread("Cliente Terminou a conexao");

                  //  Input.ReadOnly = true;
                    writer.Close();
                    reader.Close();
                    socketStream.Close();
                    connection.Close();

                    ++counter;
                }
            }
            catch (Exception erro)
            {
                MessageBox.Show("Erro: " + erro.ToString());
            }
        }

        private void PegaControlePorThread(string text)
        {
            if (this.Display.InvokeRequired)
            {
                DelegateControleDisplay d = new DelegateControleDisplay(PegaControlePorThread);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                this.Display.Text += text + "\n";
                //AutoScroll
                Display.SelectionStart = Display.Text.Length;
                Display.ScrollToCaret();             
            }
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            writer.Write("servidor >> digitou " + Input.Text);
            PegaControlePorThread("servidor >> digitou " + Input.Text);
            Input.Clear(); 
        }
    }
}



[b:3a49126811][u:3a49126811]Cliente[/u:3a49126811][/b:3a49126811]

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
// 
using System.Threading;
using System.Net.Sockets;
using System.IO;

namespace Cliente
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private delegate void DelegateControleDisplay(string texto);
        private NetworkStream saida;
        private BinaryWriter escreve;
        private BinaryReader le;
        private string msg = "";
        private Thread readThread;

        private void btnConectar_Click(object sender, EventArgs e)
        {
            readThread = new Thread(new ThreadStart(RunCliente));
            readThread.Start();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            System.Environment.Exit(System.Environment.ExitCode);
        }

        private void input_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Enter)
                {
                    escreve.Write("cliente >> digitou "+input.Text);
                    PegaControleInput("cliente >> digitou " + input.Text);
                    input.Clear(); 
                }
            }
            catch (SocketException se)
            {
                PegaControlePorThread("Erro de escrita :" + se.ToString());
            }
        }

        private void PegaControlePorThread(string text)
        {
            if (this.Display.InvokeRequired)
            {
                DelegateControleDisplay d = new DelegateControleDisplay(PegaControlePorThread);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                this.Display.Text += text + "\n";
                //AutoScroll
                Display.SelectionStart = Display.Text.Length;
                Display.ScrollToCaret();
            }
        }

        private void PegaControleInput(string text)
        {
            if (this.input.InvokeRequired)
            {
                DelegateControleDisplay d = new   DelegateControleDisplay(PegaControleInput);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                this.input.Text += text + "\n";
                //AutoScroll
                input.SelectionStart = input.Text.Length;
                input.ScrollToCaret();
            }
        }


        public void RunCliente()
        {
            TcpClient cliente;
            // instancia  TcpClient para enviar dados ao servidor
            try
            {
                PegaControlePorThread("tentando se conectar...");
                // se conectar ao servidor
                cliente = new TcpClient();
                cliente.Connect("localhost", 5000);
                // obtem o NetworkStream Associado a TcpClient
                saida = cliente.GetStream();

                // cria objetos para escrever e ler  por meio de fluxo
                escreve = new BinaryWriter(saida);
                le = new BinaryReader(saida);

                PegaControlePorThread(" E/S Stream ...");

                // input.ReadOnly = false;
                // repete ate servidor sinalizar termino
                do
                {
                    try
                    {
                        // le mensagem do servidor
                        msg = le.ReadString();
                        PegaControlePorThread(msg);
                    }
                    // trata execução se houver erro
                     catch (Exception)
                    {
                        System.Environment.Exit(System.Environment.ExitCode);                        
                    }                    
                } while (msg.ToUpper() != "FIM" && cliente.Connected);

                PegaControlePorThread("Fechando conexões ...");

                // Fecha conexoes
                escreve.Close();
                le.Close();
                saida.Close();
                cliente.Close();
                Application.Exit();
            }
            // trata execução se houver erro
            catch (Exception erro)
            {
                MessageBox.Show(erro.ToString());                
            }
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            escreve.Write("cliente >> digitou " + input.Text);
            PegaControlePorThread("cliente >> digitou " + input.Text);
            input.Clear(); 
        }
    }
}

[/i][/u]


Internautarv

Internautarv

Responder

Assista grátis a nossa aula inaugural

Assitir aula

Saiba por que programar é uma questão de
sobrevivência e como aprender sem riscos

Assistir agora

Utilizamos cookies para fornecer uma melhor experiência para nossos usuários, consulte nossa política de privacidade.

Aceitar