Fórum UDP amp; TCP/IP em C# ??? #20609
26/11/2007
0
Boa Tarde,
Alguem sabe como usar troca de Mensagens com os protocolos
[b:2907602f11]TCP/IP[/b:2907602f11] e [b:2907602f11]UDP[/b:2907602f11] ???
ou pelo menos me indicar um bom tutorial?
desde já fico grato !
:)
Alguem sabe como usar troca de Mensagens com os protocolos
[b:2907602f11]TCP/IP[/b:2907602f11] e [b:2907602f11]UDP[/b:2907602f11] ???
ou pelo menos me indicar um bom tutorial?
desde já fico grato !
:)
Internautarv
Curtir tópico
+ 0
Responder
Posts
27/11/2007
Fellix
Esse codigo axei de exemplo em algum lugar aqui funcionou perfeitamente.
PS: vc não pode usar o modo debug tah
tem q executar como uma aplicação normal
Servidor
Client
Esse é um exemplo de comunicação bem simples e funcional
xD
[]´s
PS: vc não pode usar o modo debug tah
tem q executar como uma aplicação normal
Servidor
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace ConsoleSocket
{
class Program
{
static void Main(string[] args)
{
TcpListener list = new TcpListener(8000);
list.Start();
Console.Write("Aguardando conexão");
try
{
TcpClient client = list.AcceptTcpClient();
Console.WriteLine("Conexão aceita");
NetworkStream ns = client.GetStream();
Byte[] b = new Byte[client.ReceiveBufferSize];
ns.Read(b, 0, Convert.ToInt32(client.ReceiveBufferSize));
String data = Encoding.ASCII.GetString(b);
Console.WriteLine("Cliente enviou :" + data);
Console.ReadLine();
//Envia para o cliente.
String response = "Conectado ao servidor";
byte[] sb = Encoding.ASCII.GetBytes(response);
ns.Write(sb, 0, sb.Length);
Console.WriteLine("Mensagem Enviada");
client.Close();
list.Stop();
Console.WriteLine("Comunicação encerrada");
Console.ReadLine();
}
catch (Exception e)
{
Console.Write(e.StackTrace);
}
}
}
}
Client
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace ClienteSocket
{
class Program
{
static void Main(string[] args)
{
TcpClient client = new TcpClient();
Console.WriteLine("Estabelecendo conexão");
client.Connect("127.0.0.1", 8000);
NetworkStream ns = client.GetStream();
if (ns.CanRead && ns.CanWrite)
{
Byte[] sb = Encoding.ASCII.GetBytes("Testando string");
ns.Write(sb, 0, sb.Length);
Byte[] b = new Byte[client.ReceiveBufferSize];
ns.Read(b, 0, client.ReceiveBufferSize);
String retorno = Encoding.ASCII.GetString(b);
Console.WriteLine("O servidor retornou: " + retorno);
Console.ReadLine();
}
else
{
Console.WriteLine("Não é possivel escrever ou ler do host");
Console.ReadLine();
}
client.Close();
}
}
}
Esse é um exemplo de comunicação bem simples e funcional
xD
[]´s
Responder
Gostei + 0
27/11/2007
Internautarv
Vlw!
:) pela :idea:
:) pela :idea:
Responder
Gostei + 0
Clique aqui para fazer login e interagir na Comunidade :)