Hola aqui les dejo un ejemplo de una aplicacion cliente servidor basada en sockets aun tiene pequeños bugs pero esta 100% funcional asi mismo les dejo los ejecutables para que los analizen
Descargar Proyecto —>sockets_csharp
xxxnocturnoxxx [aztekmindz.org]
Este es el codigo del servidor
namespace SocketServer
{
public class Form1 : System.Windows.Forms.Form
{
private System.ComponentModel.Container components = null;
public Form1()
{
InitializeComponent();
}
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void cmdListen_Click(object sender, System.EventArgs e)
{
try
{
m_socListener = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
IPEndPoint ipLocal = new IPEndPoint ( IPAddress.Any ,8221);
m_socListener.Bind( ipLocal );
m_socListener.Listen (4);
m_socListener.BeginAccept(new AsyncCallback ( OnClientConnect ),null);
cmdListen.Enabled = false;
}
catch(SocketException se)
{
MessageBox.Show ( se.Message );
}
}
public void OnClientConnect(IAsyncResult asyn)
{
try
{
m_socWorker = m_socListener.EndAccept (asyn);
WaitForData(m_socWorker);
}
catch(ObjectDisposedException)
{
System.Diagnostics.Debugger.Log(0,"1","\n Estado: Socket cerrado");
}
catch(SocketException se)
{
MessageBox.Show ( se.Message );
}
}
public class CSocketPacket
{
public System.Net.Sockets.Socket thisSocket;
public byte[] dataBuffer = new byte[1];
}
public void WaitForData(System.Net.Sockets.Socket soc)
{
try
{
if ( pfnWorkerCallBack == null )
{
pfnWorkerCallBack = new AsyncCallback (OnDataReceived);
}
CSocketPacket theSocPkt = new CSocketPacket ();
theSocPkt.thisSocket = soc;
soc .BeginReceive (theSocPkt.dataBuffer ,0,theSocPkt.dataBuffer.Length
,SocketFlags.None,pfnWorkerCallBack,theSocPkt);
}
catch(SocketException se)
{
MessageBox.Show (se.Message );
}
}
public void OnDataReceived(IAsyncResult asyn)
{
try
{
CSocketPacket theSockId = (CSocketPacket)asyn.AsyncState ;
int iRx = 0 ;
iRx = theSockId.thisSocket.EndReceive (asyn);
char[] chars = new char[iRx + 1];
System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
int charLen = d.GetChars(theSockId.dataBuffer, 0, iRx, chars, 0);
System.String szData = new System.String(chars);
txtDataRx.Text = txtDataRx.Text + szData;
WaitForData(m_socWorker );
}
catch (ObjectDisposedException )
{
System.Diagnostics.Debugger.Log(0,"1","\nEstado: Socket cerrado");
}
catch(SocketException se)
{
MessageBox.Show (se.Message );
}
}
private void button1_Click(object sender, System.EventArgs e)
{
try
{
Object objData = txtDataTx.Text;
byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString ());
m_socWorker.Send (byData);
}
catch(SocketException se)
{
MessageBox.Show (se.Message );
}
}
}
}
Este es el codigo del cliente
private void cmdConnect_Click(object sender, System.EventArgs e)
{
try
{
//create a new client socket …
m_socWorker = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
String szIPSelected = txtIPAddress.Text;
String szPort = txtPort.Text;
int alPort = System.Convert.ToInt16 (szPort,10);
System.Net.IPAddress remoteIPAddress = System.Net.IPAddress.Parse(szIPSelected);
System.Net.IPEndPoint remoteEndPoint = new System.Net.IPEndPoint(remoteIPAddress, alPort);
m_socWorker.Connect(remoteEndPoint);
}
catch (System.Net.Sockets.SocketException se)
{
MessageBox.Show ( se.Message );
}
}
private void cmdSendData_Click(object sender, System.EventArgs e)
{
try
{
Object objData = txtData.Text;
byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString ());
m_socWorker.Send (byData);
}
catch(System.Net.Sockets.SocketException se)
{
MessageBox.Show (se.Message );
}
}
private void cmdReceiveData_Click(object sender, System.EventArgs e)
{
try
{
byte [] buffer = new byte[1024];
int iRx = m_socWorker.Receive (buffer);
char[] chars = new char[iRx];
System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
int charLen = d.GetChars(buffer, 0, iRx, chars, 0);
System.String szData = new System.String(chars);
txtDataRx.Text = szData;
}
catch(System.Net.Sockets.SocketException se)
{
MessageBox.Show (se.Message );
}
}
private void cmdClose_Click(object sender, System.EventArgs e)
{
m_socWorker.Close ();
}
}
}
Hola, estoy intentando hacer unos sockets cliente servidor donde el servidor mande un fichero o una variable y el cliente lo lea y le conteste. Creo que a partir del tuyo lo podría hacer facilmente mi problema, supongo que será muy tonto.., pero no se como ejecutarlo en VS2005 para ir comprobando los cambios que haga. Si cojo tu código tal cual me da errores al compilar, quizás tenga mal el tipo de proyecto o algo..no se.
Gracias de antemano.Un saludo.
Hola pues mira ese codigo lo hice igual con el visual studio 2005 lo que podria estar pasando es que te falte alguna referencia a un espacio de nombres o quiza como el codigo usa eventos on_click de botones pues quiza por ahi este el error que no hayas pues to algun boton o algun otro control te sugiero que no copies y pegues el codigo si no que basandote en el crees el propio tuyo en visual studio por cierto si buscas en la seccion de c# ahi tengo un ejemplo de file transfer igual cliente servidor saludos estamos en contacto!
hola oye me dejaron un trabajo en la esc algo parecido,estoy guiandome en tu ejemplo solo k no me conecta, no me podrias decir o mandar las propiedades de los objetos del formulario estas usando textbox?
Hola ahi esta el proyecto para que lo descargues asi te das cuenta los controles que uso, suerte cualquier duda comunicate!!