socket.beginRecieve problems

I have written a program based around the example code at http://msdn.microsoft.com/library/default.asp url=/library/en-us/cpguide/html/cpconUsingNon-blockingClientSocket.asp . It's a asynch socket recieve function. After recieving the stream i don't know how i can get the string built with streambuilder, considering the function is static and the rest of my program is nonstatic. When I use breakpoints i can see that i have recieved the stream though. How do i get that string in the streambuilder for other functions than the static one Also when i want my program to listen for more streams on that socket do i have to call beginRecieve again

-Wim, c++ beginner

#pragma once

#include "StateObject.h"

using namespace System;

using namespace System::ComponentModel;

using namespace System::Collections;

using namespace System::Diagnostics;

using namespace System::Net;

using namespace System::Net::Sockets;

using namespace System::Text;

using namespace System::Threading;

namespace RevivedChat {

/// <summary>

/// Summary for Network

/// </summary>

public ref class Network : public System::ComponentModel::Component

{

public:

Network(void)

{

InitializeComponent();

//

//TODO: Add the constructor code here

//

receiveDone = gcnew ManualResetEvent(false);

}

Network(System::ComponentModel::IContainer ^container)

{

/// <summary>

/// Required for Windows.Forms Class Composition Designer support

/// </summary>

container->Add(this);

InitializeComponent();

}

static String ^response;

static ManualResetEvent ^receiveDone;

Socket^ s;

array<Byte>^ bytess;

public: void send(String ^messg){

String ^temp = "<msg user=\"WmS\">"+messg+"</msg>\0";

array<Byte>^ msg = Encoding::UTF8->GetBytes( temp );

array<Byte>^ bytess = gcnew array<Byte>(256);

// Blocks until send returns.

int byteCount = s->Send( msg );

}

public: String^ DoSocketGet( String^ server )

{

//Set up variables and String to write to the server.

Encoding^ ASCII = Encoding::ASCII;

String^ Get = "GET / HTTP/1.1\r\nHost: ";

Get->Concat( server, "test" );

array<Byte>^ByteGet = ASCII->GetBytes( Get );

array<Byte>^RecvBytes = gcnew array<Byte>(256);

String^ strRetPage = nullptr;

// IPAddress and IPEndPoint represent the endpoint that will

// receive the request.

// Get first IPAddress in list return by DNS.

try

{

s = nullptr;

IPEndPoint^ hostEndPoint;

IPAddress^ hostAddress = nullptr;

int conPort = 80;

// Get DNS host information.

IPHostEntry^ hostInfo = Dns::GetHostEntry( server );

// Get the DNS IP addresses associated with the host.

array<IPAddress^>^IPaddresses = hostInfo->AddressList;

// Evaluate the socket and receiving host IPAddress and IPEndPoint.

for ( int index = 0; index < IPaddresses->Length; index++ )

{

hostAddress = IPaddresses[ index ];

hostEndPoint = gcnew IPEndPoint( hostAddress,conPort );

// Creates the Socket to send data over a TCP connection.

s = gcnew Socket( AddressFamily::InterNetwork,SocketType::Stream,ProtocolType::Tcp );

// Connect to the host using its IPEndPoint.

s->Connect( hostEndPoint );

if ( !s->Connected )

{

// Connection failed, try next IPaddress.

strRetPage = "Unable to connect to host";

s = nullptr;

continue;

}

}

array<Byte>^ msg = Encoding::UTF8->GetBytes( "<login user=\"WmS\" />\0" );

bytess = gcnew array<Byte>(256);

// Blocks until send returns.

int byteCount = s->Send( msg );

Console::WriteLine( "Sent {0} bytes.", byteCount.ToString() );

StateObject ^state = gcnew StateObject();

state->workSocket = s;

// state->tb = debugTextBox;

// Begin receiving the data from the remote device.

s->BeginReceive( state->buffer,

0, state->BufferSize,

SocketFlags::None,

gcnew AsyncCallback(ReceiveCallback),

state);

// s->BeginReceive(bytess ,0,256, SocketFlags::None, gcnew AsyncCallback(&RevivedChat::GUI::onDataReceived), s);

if ( bytess->Length > 0 )

{

// chatTextBox->Text = chatTextBox->Text + Encoding::UTF8->GetString( bytess );

}

}

catch ( SocketException^ e )

{

Console::WriteLine("SocketException caught!!!");

Console::WriteLine("Source : ");

Console::WriteLine(e->Source);

Console::WriteLine("Message : ");

Console::WriteLine(e->Message);

}

catch ( ArgumentNullException^ e )

{

Console::WriteLine("ArgumentNULLException caught!!!");

Console::WriteLine("Source : ");

Console::WriteLine(e->Source);

Console::WriteLine("Message : ");

Console::WriteLine(e->Message);

}

catch ( NullReferenceException^ e )

{

Console::WriteLine("NULLReferenceException caught!!!");

Console::WriteLine("Source : ");

Console::WriteLine(e->Source);

Console::WriteLine("Message : ");

Console::WriteLine(e->Message);

}

catch ( Exception^ e )

{

Console::WriteLine("Exception caught!!!");

Console::WriteLine("Source : ");

Console::WriteLine(e->Source);

Console::WriteLine("Message : ");

Console::WriteLine(e->Message);

}

return strRetPage;

}

protected:

/// <summary>

/// Clean up any resources being used.

/// </summary>

~Network()

{

if (components)

{

delete components;

}

}

private:

/// <summary>

/// Required designer variable.

/// </summary>

System::ComponentModel::Container ^components;

private: static void ReceiveCallback( IAsyncResult ^ar ) {

String ^temp = gcnew String("");

try {

// Retrieve the state object and the client socket

// from the asynchronous state object.

StateObject ^state = (StateObject^) ar->AsyncState;

Socket ^client = state->workSocket;

// Read data from the remote device.

int bytesRead = client->EndReceive(ar);

if (bytesRead > 0) {

// There might be more data, so store the data received so far.

state->sb->Append(Encoding::UTF8->GetString(state->buffer,0,bytesRead));

// Get the rest of the data.

temp = state->sb->ToString();

response = state->sb->ToString();

client->BeginReceive(state->buffer,0,state->BufferSize,SocketFlags::None,

gcnew AsyncCallback(ReceiveCallback), state);

} else {

// All the data has arrived; put it in response.

if (state->sb->Length > 1) {

temp = state->sb->ToString();

response = state->sb->ToString();

state->sb = gcnew StringBuilder();

//RevivedChat::GUI::debugTextBox::Text = response;

//state->tb->Text = state->tb->Text + "\n" + response;

//writeResponse(response);

}

// Signal that all bytes have been received.

receiveDone->Set();

}

//ManualResetEvent ^receiveDone;

//receiveDone->sendDone();

receiveDone->Set();

temp = state->sb->ToString();

response = state->sb->ToString();

int temp = 0;

} catch (Exception ^e) {

Console::WriteLine( e->Message );

//debugTextBox->Text = debugTextBox->Text + "\n" + e->ToString();

}

}

#pragma region Windows Form Designer generated code

/// <summary>

/// Required method for Designer support - do not modify

/// the contents of this method with the code editor.

/// </summary>

void InitializeComponent(void)

{

components = gcnew System::ComponentModel::Container();

}

#pragma endregionshould j

};

}



Answer this question

socket.beginRecieve problems

  • CougarDave

    Also when i want my program to listen for more streams on that socket do i have to call beginRecieve again

    Yes, you need to issue another BeginReceive to read more data from the stream. Only once the stream returns 0 bytes has the remote side completed sending and closed their socket.



  • socket.beginRecieve problems