473,804 Members | 3,453 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

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

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

PatentRequestPa cket packet = new PatentRequestPa cket();
PatentRequestPa cket ackPacket = new PatentRequestPa cket();

int m_nPort = 50055;
Socket ConnectSocket = new
Socket(AddressF amily.InterNetw ork,SocketType. Stream,Protocol Type.Tcp);

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

IPEndPoint ipEnd = new IPEndPoint(IPAd dress.Parse("12 7.0.0.1"),
50055);
ConnectSocket.C onnect(ipEnd);
NetworkStream networkStream = socketForServer .GetStream();

int bytesSent;
int m_nNumPages = -1;
packet.Key = m_strKey.ToChar Array();
packet.PatentNu mber= "6655414".ToCha rArray();
packet.NumPages = m_nNumPages;
byte[] BYTE = new byte[10000];
BYTE = RawSerialize(ac kPacket);
byte[] BYTE2 = {Convert.ToByte ('0')};
BYTE2= RawSerialize(pa cket);

ConnectSocket.S end(BYTE);
ConnectSocket.R eceive(BYTE2);

// Rawserialize is a method defined in the class
// public static byte[] RawSerialize( object anything )
// {
// int rawsize = Marshal.SizeOf( anything );
// IntPtr buffer = Marshal.AllocHG lobal( rawsize );
// Marshal.Structu reToPtr( anything, buffer, false );
// byte[] rawdatas = new byte[ rawsize ];
// Marshal.Copy( buffer, rawdatas, 0, rawsize );
// Marshal.FreeHGl obal( buffer );
// return rawdatas;
// }

Jan 31 '06 #1
6 2240
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."

Jan 31 '06 #2
Hi,

byte[] BYTE = new byte[10000]; BYTE = RawSerialize(ac kPacket);


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(pa cket);
The same thing, why you assign BTE2 like that?
ConnectSocket.S end(BYTE);
ConnectSocket.R eceive(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.

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
Jan 31 '06 #3
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 CBandToolBarCtr l::SendMessage( CString message)

{
PatentRequestPa cket packet, ackPacket;

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

//----------------------
// Create a SOCKET for connecting to server
SOCKET ConnectSocket;
ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ConnectSocket == INVALID_SOCKET) {
MessageBox("Fai led 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.s in_family = AF_INET;

clientService.s in_addr.s_addr = inet_addr( "127.0.0.1" );

clientService.s in_port = htons( m_nPort );

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

for(int nAttempt=1; nAttempt<=5; nAttempt++)
{
Sleep(100*nAtte mpt);
status = connect( ConnectSocket, (SOCKADDR*)
&clientServi ce, sizeof(clientSe rvice) );

if(status != SOCKET_ERROR)
break;
}

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

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

strcpy(packet.K ey,m_strKey);
strcpy(packet.P atentNumber,mes sage);
packet.NumPages = m_nNumPages;

//----------------------
// Send and receive data.
for(nAttempt=1; nAttempt<5; nAttempt++)
{
Sleep(100*nAtte mpt);
bytesRecv = recv( ConnectSocket, (char*)
&ackPacket, sizeof(ackPacke t), 0);
if(bytesRecv)
{
//CString str;
//str.Format("Att empt:%d Bytes:%d
packetsize:%d", nAttempt,bytesR ecv,sizeof(pack et));
//MessageBox(str) ;
break;
}

}

if(bytesRecv==0 )

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

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

//MessageBox("dat a 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.

Jan 31 '06 #4
Yes i have to communicate with an application (Same endpoint i guess)
whose call is made in the above VC code.. kindly help

Jan 31 '06 #5

"Khadim" <as***********@ gmail.com> wrote in message
news:11******** **************@ g44g2000cwa.goo glegroups.com.. .

[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.

Jan 31 '06 #6
Hi,

"Khadim" <as***********@ gmail.com> wrote in message
news:11******** **************@ g44g2000cwa.goo glegroups.com.. .
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.

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
Jan 31 '06 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
1882
by: Graham | last post by:
Can anyone tell me how to detect when a client socket connection has failed (ie remote equipment power failure) using VB.net. Thanks in advance
1
5228
by: Jim P. | last post by:
I'm having trouble returning an object from an AsyncCallback called inside a threaded infinite loop. I'm working on a Peer2Peer app that uses an AsyncCallback to rerieve the data from the remote peer. I have no problem connecting the peers and streaming Network Streams. When the incoming data is finished recieving, I act upon it. This works great as long as all of the code is inside my form. I want to build the networking code into a...
0
1701
by: Johann Blake | last post by:
I am using the TcpClient to connect to a web site. I then open a NetworkStream and read the contents that are being sent back. The problem is that I have no idea when the remote host is finished sending data. It is sending a web page but it doesn't use the Content-Length header to indicate the size. While I can use the DataAvailable property, it is well known that you cannot rely on this to know when no more data is available. What I...
4
3301
by: Vicente García | last post by:
Hello!! sorry for my english, I've made an application that ran correctly for 3 days, It's a service, however in the third day the application failed because of "An existing connection was forcibly closed by the remote host" exception, and then the CPU usage was 95 %. I don't know why it happens :( The service is always runs and other application works with the service using sockets, the exception occur when the service tried to send a...
4
4021
by: gsimmons | last post by:
I've been researching multi-threaded WinForms apps and thread synchronization stuff for a couple days since I'm working on refactoring a multi-threaded GUI app at work and want to be sure it's rock solid/thread-safe. I've seen all the posts about using BeginInvoke to have worker threads interact with the UI. My question is this: I created a plain old Windows Form application (VS.NET 2005) with a blank form, built it (release build), ran...
4
2232
by: Anbu | last post by:
Hi All, I'm using the Cassini component in my desktop application to create a web site to host the web services. The application works fine in normal scenario. If the system is kept idle for some time, the application getting terminated with the following error: Unhandled Exception : An existing connection was forcibly closed by the remote host at System.Net.Sockets.Socket.Send(Byte buffer, Int32 offset, Int32
3
1965
by: Wayne And Miles | last post by:
I have created a server application that listens for connections using the TCPListener class. When I connect to the server using a client on the same machine as the server, all works as expected. However, when I attempt to connect to the server application from a client on a remote machine on my LAN, the connection is refused. I have used Ethereal to confirm that the request from the client is being received on the server machine. I...
10
7410
by: Hendrik van Rooyen | last post by:
While doing a netstring implementation I noticed that if you build a record up using socket's recv(1), then when you close the remote end down, the recv(1) hangs, despite having a short time out of 0.1 set. If however, you try to receive more than one char, (I tested with 3, did not try 2), then when you shut the remote end down you do not get a time out, but an empty string - the normal end of file, I suppose. Has anybody else seen...
7
4021
by: Guy Davidson | last post by:
Hi Folks, I'm having some issues with an small socket based server I'm writing, and I was hoping I could get some help. My code (attached below) us supposed to read an HTTP Post message coming from a power meter, parse it, and return a proper HTTP 200 Ok message. The problem is that the socket fails to send the entire message as one message, creating a fragmented message which the power meter then fails to read and accept.
0
9705
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9576
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10567
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9138
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7613
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6847
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4291
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3809
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2983
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.