473,545 Members | 527 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 2231
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
1867
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
5197
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...
0
1683
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...
4
3285
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...
4
3998
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...
4
2226
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...
3
1942
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...
10
7372
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...
7
4005
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...
0
7464
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...
0
7396
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...
1
7413
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7751
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
4943
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...
0
3449
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3440
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1874
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
0
700
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...

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.