473,685 Members | 3,111 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Socket.Send is slow when sending within same process

There is two examples of code.

Example 1. Send and Receive within the same process. Put this code in a
console app called SendAndReceive and run the code.

using System;
using System.Collecti ons.Generic;
using System.Net;
using System.Net.Sock ets;
using System.Runtime. Serialization.F ormatters.Binar y;
using System.Text;
using System.Threadin g;

namespace ConsoleApplicat ion3
{
class Program
{
static void Main(string[] args)
{
SocketReceive sr = new SocketReceive() ;
Thread tsr = new Thread(new ThreadStart(sr. Process));
tsr.IsBackgroun d = true;
tsr.Start();

SocketSend ss = new SocketSend();
Thread tss = new Thread(new ThreadStart(ss. Process));
tss.IsBackgroun d = true;
tss.Start();

while (tsr.IsAlive || tss.IsAlive)
{
Thread.Sleep(10 0);
}
}
}

class SocketSend
{
public void Process()
{
// Register the socket
IPEndPoint endPoint = new
IPEndPoint(Dns. GetHostAddresse s(Dns.GetHostNa me())[0], 7001);

Socket socket = new Socket(AddressF amily.InterNetw ork,
SocketType.Stre am,
ProtocolType.IP );
try
{
int max = 600000;
socket.Connect( endPoint);
long start = start = DateTime.Now.Ti cks; ;
long time1 = 0;
int completed = 0;
for (int i = 0; i <= max; i++)
{
if ((i % 1000) == 0)
Console.WriteLi ne("Sending {0}", i);
SendLiteMessage (socket, i);
completed++;
time1 = DateTime.Now.Ti cks;
if (((time1 - start) / 10000) 1000)
{
Console.WriteLi ne("Sent {0} in {1}(ms)", completed,
((time1 - start) / 10000));
start = DateTime.Now.Ti cks;
completed = 0;
}
}
}

catch (Exception ex)
{
Console.WriteLi ne(ex.Message);
}
finally
{
socket.Shutdown (SocketShutdown .Both);
socket.Close();
}
}

private void SendLiteMessage (Socket socket, int count)
{
byte[] bas = new byte[2048];
bas[0] = (byte)count;

long start = start = DateTime.Now.Ti cks; ;
socket.Send(bas , SocketFlags.Non e);
long time1 = DateTime.Now.Ti cks;
//Console.WriteLi ne("Socket Send took {0}", (time1 - start));
}

}

class SocketReceive
{
private object ReceiveMessageL ite(NetworkStre am ns, int count)
{
byte[] bas = new byte[2048];
int read = ns.Read(bas, 0, bas.Length);
return bas;
}

public void Process()
{
IPEndPoint endPoint = new
IPEndPoint(Dns. GetHostAddresse s(Dns.GetHostNa me())[0], 7001);
try
{
Console.WriteLi ne("Waiting for Sender...");
TcpListener listener = new TcpListener(end Point.Address,
7001);

listener.Start( );
TcpClient client = listener.Accept TcpClient();
client.ReceiveB ufferSize = 32768;
NetworkStream ns = client.GetStrea m();
long start = start = DateTime.Now.Ti cks; ;
long time1 = 0;
int completed = 0;
for (int i = 0; i < 600000; i++)
{
if ((i % 1000) == 0)
Console.WriteLi ne("Receiving {0}", i);

object obj = ReceiveMessageL ite(ns, i);
completed++;
time1 = DateTime.Now.Ti cks;
if (((time1 - start) / 10000) 1000)
{
Console.WriteLi ne("Received {0} in {1}(ms)",
completed, ((time1 - start) / 10000));
start = DateTime.Now.Ti cks;
completed = 0;
}
}
}
catch (Exception ex)
{
Console.WriteLi ne(ex.Message);
}
finally
{
}
}
}
}

Example 2. Put this code in a console app called Receive
using System;
using System.Collecti ons.Generic;
using System.Net;
using System.Net.Sock ets;
using System.Runtime. Serialization.F ormatters.Binar y;
using System.Text;
using System.Threadin g;

namespace ConsoleApplicat ion3
{
class Program
{
static void Main(string[] args)
{
SocketReceive sr = new SocketReceive() ;
Thread tsr = new Thread(new ThreadStart(sr. Process));
tsr.IsBackgroun d = true;
tsr.Start();

while (tsr.IsAlive)
{
Thread.Sleep(10 0);
}
}
}

class SocketReceive
{
private object ReceiveMessageL ite(NetworkStre am ns, int count)
{
byte[] bas = new byte[2048];
int read = ns.Read(bas, 0, bas.Length);
return bas;
}

public void Process()
{
IPEndPoint endPoint = new
IPEndPoint(Dns. GetHostAddresse s(Dns.GetHostNa me())[0], 7001);
try
{
Console.WriteLi ne("Waiting for Sender...");
TcpListener listener = new TcpListener(end Point.Address,
7001);

listener.Start( );
TcpClient client = listener.Accept TcpClient();
client.ReceiveB ufferSize = 32768;
NetworkStream ns = client.GetStrea m();
long start = start = DateTime.Now.Ti cks; ;
long time1 = 0;
int completed = 0;
for (int i = 0; i < 600000; i++)
{
if ((i % 1000) == 0)
Console.WriteLi ne("Receiving {0}", i);

object obj = ReceiveMessageL ite(ns, i);
completed++;
time1 = DateTime.Now.Ti cks;
if (((time1 - start) / 10000) 1000)
{
Console.WriteLi ne("Received {0} in {1}(ms)",
completed, ((time1 - start) / 10000));
start = DateTime.Now.Ti cks;
completed = 0;
}
}
}
catch (Exception ex)
{
Console.WriteLi ne(ex.Message);
}
finally
{
}
}
}
}
Example 2. Put this code in a console app called Send.
using System;
using System.Collecti ons.Generic;
using System.Net;
using System.Net.Sock ets;
using System.Runtime. Serialization.F ormatters.Binar y;
using System.Text;
using System.Threadin g;

namespace ConsoleApplicat ion3
{
class Program
{
static void Main(string[] args)
{
SocketSend ss = new SocketSend();
Thread tss = new Thread(new ThreadStart(ss. Process));
tss.IsBackgroun d = true;
tss.Start();

while (tss.IsAlive)
{
Thread.Sleep(10 0);
}
}
}

class SocketSend
{
public void Process()
{
// Register the socket
IPEndPoint endPoint = new
IPEndPoint(Dns. GetHostAddresse s(Dns.GetHostNa me())[0], 7001);

Socket socket = new Socket(AddressF amily.InterNetw ork,
SocketType.Stre am,
ProtocolType.IP );
try
{
int max = 600000;
socket.Connect( endPoint);
long start = start = DateTime.Now.Ti cks; ;
long time1 = 0;
int completed = 0;
for (int i = 0; i <= max; i++)
{
if ((i % 1000) == 0)
Console.WriteLi ne("Sending {0}", i);
SendLiteMessage (socket, i);
completed++;
time1 = DateTime.Now.Ti cks;
if (((time1 - start) / 10000) 1000)
{
Console.WriteLi ne("Sent {0} in {1}(ms)", completed,
((time1 - start) / 10000));
start = DateTime.Now.Ti cks;
completed = 0;
}
}
}

catch (Exception ex)
{
Console.WriteLi ne(ex.Message);
}
finally
{
socket.Shutdown (SocketShutdown .Both);
socket.Close();
}
}

private void SendLiteMessage (Socket socket, int count)
{
byte[] bas = new byte[2048];
bas[0] = (byte)count;

long start = start = DateTime.Now.Ti cks; ;
socket.Send(bas , SocketFlags.Non e);
long time1 = DateTime.Now.Ti cks;
//Console.WriteLi ne("Socket Send took {0}", (time1 - start));
}

}

}

Run Receive and then Send. Compare the received about with Example 1 you
will see example 2 will be quicker.

Let me know your outcome.

Thanks,
Oct 6 '06 #1
0 3156

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

Similar topics

3
4629
by: Robert A. van Ginkel | last post by:
Hello Fellow Developer, I use the System.Net.Sockets to send/receive data (no tcpclient/tcplistener), I made a receivethread in my wrapper, the receivethread loops/sleeps while waiting for data and then fires a datareceived event. Within the waitingloop there is a timeout function, but I want the the 'last-time-socket-used' variable set when the socket is finished sending. When I send by System.Net.Sockets.Socket.Send(buffer()) (<--this...
5
3679
by: John Sheppard | last post by:
Hi all, I am not sure that I am posting this in the right group but here it goes anyway. I am new to socket programming and I have been searching on the internet to the questions I am about to pose but have been unsuccessful in finding the answers so far. Either because my understanding of sockets isn't where it needs to be or my questions are too basic. My programming environment is Windows XP, Visual Studio .NET 2003 and C#. So here it...
4
18115
by: Chris Tanger | last post by:
Context: C# System.Net.Sockets Socket created with constructor prarmeters Internetwork, Stream and TCP everything else is left at the default parameters and options except linger may be changed as I find appropriate. I am using the socket asynchronously by calling the BeingSend and BeginReceive calls. I would like to be able to call shutdown and close asynchronously if possible.
5
4490
by: kuba bogaczewicz | last post by:
Hello all, for my school project I have to write a small peer-2-peer application using Sockets, and I've chosen C# for the task. I've been doing some research on the topic, and I would really appreciate if someone checked if I got all things right. I am going to use asynchronous connections, and here comes some of my doubts: -> I want to send each message in a scheme: 4 bytes with the size, then actual message. According to MSDN I got...
2
2800
by: Nuno Magalhaes | last post by:
How to check for a closed http socket without losing any data? (MSDN says to send something to server). Somewhere in my code (after sending the http header in plain text) I'm doing a loop with: Loop:---------------- Socket.Receive //receive http data chunks Socket.Send //'/r/n' data to check if connection is active ------------------------ The problem is that when connection is closed by the http server, the send socket function...
3
4297
by: BuddyWork | last post by:
Hello, Could someone please explain why the Socket.Send is slow to send to the same process it sending from. Eg. Process1 calls Socket.Send which sends to the same IP address and port, the receiver is running within Process1. If I move the receiver into Process2 then its fast. Please can someone explain.
2
1343
by: linuxfedora | last post by:
What is the best way to write the following application: The Main GUI thread will try to send packet to other side in the network, it could be very slow network or very fast network. How can i ensure that the sending packet will not miss and the program is effective? I tried to use Socket::Send to send data, but if it is in a very slow network, then it will block the main GUI for responding, right? Then How can i acheive this purpose?
2
3667
by: manasap | last post by:
Hi all! I've written a server and a client application using asynchronous sockets.The client sends data packets for every 7 seconds.The server receives the packets. This process proceeds smoothly without any errors but,sometimes I get the following error. "An existing connection was forcibly closed by the remote host." Why is this happening when i am not closing the client program? Could someone guide me in this issue
0
8570
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
8925
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8758
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
8773
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7584
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...
0
5790
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();...
0
4299
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2936
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
2198
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.