nothing is returning from remote application.... socket problem

K

Khadim

I am using the following code, don't know what am i missing. in BYTE2 I
am not getting any information from the remote application.
any guidance would be highly appreciated, thanking you in advance

// PatentRequestPaket is a structure defined above in the class
//public struct PatentRequestPacket
//{
// public char[] Key;// = new char[15];
// public char[] PatentNumber;// = new char[20];
// public int NumPages;
//}

PatentRequestPacket packet = new PatentRequestPacket();
PatentRequestPacket ackPacket = new PatentRequestPacket();

int m_nPort = 50055;
Socket ConnectSocket = new
Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

TcpClient socketForServer;
try
{
socketForServer = new TcpClient("127.0.0.1", 50055);
}
catch
{
Console.WriteLine(
"Failed to connect to server at {0}:999", "localhost");
return;
}

IPEndPoint ipEnd = new IPEndPoint(IPAddress.Parse("127.0.0.1"),
50055);
ConnectSocket.Connect(ipEnd);
NetworkStream networkStream = socketForServer.GetStream();

int bytesSent;
int m_nNumPages = -1;
packet.Key = m_strKey.ToCharArray();
packet.PatentNumber= "6655414".ToCharArray();
packet.NumPages = m_nNumPages;
byte[] BYTE = new byte[10000];
BYTE = RawSerialize(ackPacket);
byte[] BYTE2 = {Convert.ToByte('0')};
BYTE2= RawSerialize(packet);

ConnectSocket.Send(BYTE);
ConnectSocket.Receive(BYTE2);

// Rawserialize is a method defined in the class
// public static byte[] RawSerialize( object anything )
// {
// int rawsize = Marshal.SizeOf( anything );
// IntPtr buffer = Marshal.AllocHGlobal( rawsize );
// Marshal.StructureToPtr( anything, buffer, false );
// byte[] rawdatas = new byte[ rawsize ];
// Marshal.Copy( buffer, rawdatas, 0, rawsize );
// Marshal.FreeHGlobal( buffer );
// return rawdatas;
// }
 
N

Nick Hounsome

Apart from any other problem you should always check the return from
receive:

"If you are using a connection-oriented Socket, the Receive method will read
as much data as is available, up to the size of the buffer. If the remote
host shuts down the Socket connection with the Shutdown method, and all
available data has been received, the Receive method will complete
immediately and return zero bytes."
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

byte[] BYTE = new byte[10000];
BYTE = RawSerialize(ackPacket);

Why you do this ? you create an array of 1000 bytes and in the next line you
just make it inaccesible?

byte[] BYTE2 = {Convert.ToByte('0')};
BYTE2= RawSerialize(packet);

The same thing, why you assign BTE2 like that?
ConnectSocket.Send(BYTE);
ConnectSocket.Receive(BYTE2);

Are you sending and receiving in the same endpoint ?

You are supposted to send from socketForServer and receive in ConnectSocket



Also I do not like the weay you convert your struct to byte[] you should
not have to p/invoke nothign for this.
 
K

Khadim

Mr. Ignacio Machin, thank you very much for your reply. actually i m
really not getting through with this thing... i have no previous
experience with sockets. I would appreciate if you could guide me more
in this respect..... following is the section of code which i am trying
to translate in C#

void CBandToolBarCtrl::SendMessage(CString message)

{
PatentRequestPacket packet, ackPacket;

int m_nPort = 50055;
//----------------------
// Initialize Winsock
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != NO_ERROR)
MessageBox("Error at WSAStartup()");

//----------------------
// Create a SOCKET for connecting to server
SOCKET ConnectSocket;
ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ConnectSocket == INVALID_SOCKET) {
MessageBox("Failed to create socket");
//printf("Error at socket(): %ld\n",
WSAGetLastError());
WSACleanup();
return;
}

//----------------------
// The sockaddr_in structure specifies the address family,
// IP address, and port of the server to be connected to.
sockaddr_in clientService;

clientService.sin_family = AF_INET;

clientService.sin_addr.s_addr = inet_addr( "127.0.0.1" );

clientService.sin_port = htons( m_nPort );



//----------------------
// Connect to server.
int status;

for(int nAttempt=1; nAttempt<=5; nAttempt++)
{
Sleep(100*nAttempt);
status = connect( ConnectSocket, (SOCKADDR*)
&clientService, sizeof(clientService) );

if(status != SOCKET_ERROR)
break;
}

if(status == SOCKET_ERROR)
{
MessageBox("Failed to connect to Patent
Hunter");
WSACleanup();
return;
}

//----------------------
// Declare and initialize variables.
int bytesSent;
int bytesRecv = SOCKET_ERROR;

strcpy(packet.Key,m_strKey);
strcpy(packet.PatentNumber,message);
packet.NumPages = m_nNumPages;

//----------------------
// Send and receive data.


for(nAttempt=1; nAttempt<5; nAttempt++)
{
Sleep(100*nAttempt);
bytesRecv = recv( ConnectSocket, (char*)
&ackPacket, sizeof(ackPacket), 0);
if(bytesRecv)
{
//CString str;
//str.Format("Attempt:%d Bytes:%d
packetsize:%d",nAttempt,bytesRecv,sizeof(packet));
//MessageBox(str);
break;
}

}

if(bytesRecv==0)

{
MessageBox("Couldn't receive the connection
acknowledgement from the Patent Hunter");
return;
}

bytesSent = send( ConnectSocket, (char*) &packet,
sizeof(packet), 0 );

//MessageBox("data sent");
//printf( "Bytes Sent: %ld\n", bytesSent );
WSACleanup();

}

i have searched diffrent forums and have gathered that C# code which
you have seen... socketForServer belongs to TcpClient class and there
is no method to send in it.
 
K

Khadim

Yes i have to communicate with an application (Same endpoint i guess)
whose call is made in the above VC code.. kindly help
 
N

Nick Hounsome

[lots of stuff]

khadim - I can't be bothered to check all your code but I will tell you one
tip for TCP usage that you haven't covered:

There is (in general) no connection between the number of bytes in a send
and the number of bytes in a receive - The implementation and the network
are entitled to chop it up into any number of chunks each of which may
require a separate call to receive - this is not a C# or .NET thing it is
TCP and therefore in any low level socket interface.

consequently all low level receive routines have to accumulate bytes into a
buffer with repeated receives until they know that they have a complete
message or that the other end has closed (usualy indicated by a receive of 0
bytes).

with the async routines this gets quite messy so i tend to avoid them and
use a separate thread and the synchronous methods.

Usually what happens is that people just send small messages which means
that they will usually get away with it until they increase their package
size to greater than one ethernet payload and their app fails.
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

Khadim said:
Mr. Ignacio Machin, thank you very much for your reply. actually i m
really not getting through with this thing... i have no previous
experience with sockets. I would appreciate if you could guide me more
in this respect..... following is the section of code which i am trying
to translate in C#

Does this C++ code works?

As another poster said, I cannot check in details your code

I noted a couple of erros in your C# code, basically that you are
sending/receiving using the same endpoint, did u changed it?


Why you need to translate the code in the first place? just create your own.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top