[MonoTouch] Socket Connection

jowi j.wiersma17 at chello.nl
Sat Dec 17 07:36:52 EST 2011


You should have a callback to your OnDataReceived, and actively wait for
data. This should work:


Socket m_clientSocket;
AsyncCallback m_pfnCallBack;
		
public void Connect()
{     
    m_clientSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
    IPEndPoint ipEnd = new IPEndPoint(IPAddress.Parse("192.168.1.23"),
9999);
                
    m_clientSocket.Connect(ipEnd);

    if (m_clientSocket.Connected)
        WaitForData();
}
	
void WaitForData()
{
    if (m_pfnCallBack == null)
        m_pfnCallBack = new AsyncCallback(OnDataReceived);

    SocketPacket theSocPkt = new SocketPacket();
    theSocPkt.thisSocket = m_clientSocket;

    // Start listening to the data asynchronously
    m_clientSocket.BeginReceive(theSocPkt.dataBuffer, 0,
theSocPkt.dataBuffer.Length, SocketFlags.None, m_pfnCallBack, theSocPkt);
}
		
class SocketPacket
{
    public Socket thisSocket;
    public byte[] dataBuffer = new byte[64];
}

void OnDataReceived(IAsyncResult iar)
{            
    SocketPacket theSockId = (SocketPacket)iar.AsyncState;
           
    int bytesRead = theSockId.thisSocket.EndReceive(iar);
                                
    byte[] data = new byte[bytesRead];
    Buffer.BlockCopy(theSockId.dataBuffer, 0, data, 0, bytesRead);
                              
    WaitForData();
}	

--
View this message in context: http://monotouch.2284126.n4.nabble.com/Socket-Connection-tp4207965p4208089.html
Sent from the MonoTouch mailing list archive at Nabble.com.


More information about the MonoTouch mailing list