473,652 Members | 3,045 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how to write a file faster

375 Contributor
Hi All ,

I have with me a server socket program, I am receiving all the clients, but what happens is i have to write it into a file.
This consumes time.

So we do not have a data loss, but as the time taken to write into the log file increases, some of the data does not get written.

This is the code

//ONLY SHOBA
Expand|Select|Wrap|Line Numbers
  1. #define debug
  2. using System;
  3. using System.Collections.Generic;
  4. using System.ComponentModel;
  5. using System.Data;
  6. using System.Data.SqlClient;
  7. using System.Drawing;
  8. using System.Text;
  9. using System.Net;
  10. using GeoBoundary;
  11. using LLUTMConvert;
  12. using System.Collections.Specialized;
  13. using System.IO;
  14. using System.Globalization;
  15. using System.Net.Sockets;
  16. using System.Collections;
  17. using System.Threading;
  18. using System.Configuration;
  19. using System.Messaging;
  20. using AmiComServerConsole;
  21. using Microsoft.VisualBasic;
  22. using Microsoft.VisualBasic.CompilerServices;
  23. using System.Runtime.CompilerServices;
  24. using System.Windows.Forms;
  25. namespace SocketServer
  26. {
  27.  
  28.     public sealed class SingletonExample
  29.     {
  30.         private static SingletonExample instance = null;
  31.         private static readonly object objectlockCheck = new object();
  32.  
  33.         private SingletonExample()
  34.         {
  35.         }
  36.  
  37.         public static SingletonExample Instance
  38.         {
  39.             get
  40.             {
  41.                 lock (objectlockCheck)
  42.                 {
  43.                     if (instance == null)
  44.                         instance = new SingletonExample();
  45.                     return instance;
  46.                 }
  47.             }
  48.  
  49.  
  50.  
  51.         }
  52.         public void WriteLogMessage(string strMessage)
  53.         {
  54.             try
  55.             {
  56.  
  57.                 string text4 = "D:\\COMSERVER\\9.7\\dummysobha\\bin\\Debug\\Log \\Log_first_8.11.2008.txt";
  58.                 StreamWriter writer1 = File.AppendText(text4);
  59.                 writer1.WriteLine(DateTime.Now.ToString() + " " + strMessage);
  60.                 writer1.Close();
  61.             }
  62.             catch (Exception)
  63.             {
  64.             }
  65.         }
  66.     }
  67.  
  68.     public class StateObject  //class created by mahesh to clear the duplicate records
  69.     {
  70.         // Client socket.
  71.         public Socket workSocket = null;
  72.         // Size of receive buffer.
  73.         public const int BufferSize = 5000;
  74.         // Receive buffer.
  75.         public byte[] buffer = new byte[BufferSize];
  76.         // Received data string.
  77.         public string sb;
  78.  
  79.     }
  80.  
  81.  
  82.  
  83.  
  84.  
  85.  
  86.     class Program
  87.     {
  88.  
  89.  
  90.         private string DatabaseType;
  91.  
  92.  
  93.         public static int i=0;
  94.         public string strConOra;
  95.         public string strConSql;
  96.  
  97.         public AsyncCallback pfnWorkerCallBack;
  98.         private Socket m_mainSocket;
  99.  
  100.         public int port = 7777;
  101.         public byte[] m_byBuff = new byte[5000];
  102.         public int flag2 = 0;
  103.         public string queuePath;
  104.         private string strDateFormat;
  105.         private string strLocation;
  106.  
  107.         public byte[] inValue = new byte[] { 1, 0, 0, 0, 0, 0, 5, 0, 1, 0, 0, 0 }; //1 -Minutes // 0,5 --   0 --seconds  6th parameter-->seconds 7th parameter-->minutes
  108.  
  109.         public byte[] outvalue = new byte[10];
  110.  
  111.         private string m_strConnection;
  112.         private SqlConnection ocon;
  113.         private SqlConnection ocon2;
  114.  
  115.         public long Mylockcounter = 0;
  116.  
  117.         private SqlConnection MyCon;
  118.         public string Conn;
  119.         public Program()
  120.         {
  121. #if debug
  122.             this.queuePath = ".\\private$\\AMI";
  123. #else
  124.             this.queuePath = ".\\private$\\AMI";
  125. #endif
  126.             this.m_strConnection = ConfigurationSettings.AppSettings["Connection"];
  127.             this.strDateFormat = null;
  128.             this.strLocation = null;
  129.             StartListen();
  130.  
  131.  
  132.         }
  133.         public void StartListen()
  134.         {
  135.  
  136.  
  137.             try
  138.             {
  139.                 NameValueCollection collection1 = ConfigurationSettings.AppSettings;
  140.                 //string portStr = this.IPPort;
  141.                 //int port = System.Convert.ToInt32(portStr);
  142.                 // Create the listening socket...
  143.                 m_mainSocket = new Socket(AddressFamily.InterNetwork,
  144.                                           SocketType.Stream,
  145.                                           ProtocolType.Tcp);
  146.                 IPAddress ip;
  147.  
  148. #if debug
  149.                 string ipstr = "192.168.0.20";
  150. #else
  151.                 string ipstr = "192.168.3.7";
  152. #endif
  153.  
  154.                 ip = IPAddress.Parse(ipstr);
  155.  
  156.                 IPEndPoint ipLocal = new IPEndPoint(ip, port);
  157.                 //// Bind to local IP Address...
  158.                 m_mainSocket.Bind(ipLocal);
  159.                 //// Start listening...
  160.                 m_mainSocket.Listen(400);
  161.  
  162.  
  163.  
  164.                 // New method
  165.  
  166.                 string text5 = "provider=OraOLEDB.Oracle.1;Persist Security Info=False;User ID=VTS;password=VTS;Data Source=DMGIS";
  167.                 string text4 = "workstation id=192.168.0.20;Data Source=192.168.0.20;User ID=sa;Password=1234;Initial Catalog=VTS1;Max Pool Size=300;Min Pool Size=1;Pooling=True";
  168.                 this.Conn = "workstation id=192.168.0.20;Data Source=192.168.0.20;User ID=sa;Password=1234;Initial Catalog=VTS1;Max Pool Size=300;Min Pool Size=1;Pooling=True";
  169.  
  170.                 MyCon = new SqlConnection(this.Conn);
  171.                 MyCon.Open();
  172.  
  173.  
  174.                 this.DatabaseType = "SQL";
  175.                 this.strDateFormat = "us";
  176.                 if (this.strLocation == null)
  177.                 {
  178.                     this.strLocation = "Road name not available";
  179.                 }
  180.                 if (this.DatabaseType == "SQL")
  181.                 {
  182.                     this.strConSql = text4;
  183.                 }
  184.                 else if (this.DatabaseType == "ORACLE")
  185.                 {
  186.                     this.strConOra = text5;
  187.                 }
  188.                 else
  189.                 {
  190.                     WriteErrorLogMessage("Proper database was not mentioned");
  191.                 }
  192.                 collection1 = null;
  193.  
  194.              while (true)
  195.                 {
  196.  
  197.                     m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
  198.                     Thread.Sleep(2000);
  199.                 }
  200.  
  201.             }
  202.             catch (Exception e1)
  203.             {
  204.             }
  205.         }
  206.  
  207.  
  208.         public void OnClientConnect(IAsyncResult asyn)
  209.         {
  210.             try
  211.             {
  212.                 Socket msocket;
  213.  
  214.                 msocket = m_mainSocket.EndAccept(asyn);
  215.  
  216.                 msocket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.KeepAlive, 1);
  217.                 msocket.IOControl(IOControlCode.KeepAliveValues, inValue, outvalue); 
  218.                 WaitForData(msocket);
  219.                 m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
  220.  
  221.             }
  222.  
  223.             catch (Exception e1)
  224.             {
  225.                // WriteErrorLogMessage(e1.Message);
  226.             }
  227.         }
  228.  
  229.        public void WaitForData(System.Net.Sockets.Socket soc)
  230.         {
  231.             try
  232.             {
  233.                 Console.WriteLine("\n");
  234.                 Console.WriteLine("WaitforData");
  235.                 Console.WriteLine("\n");
  236.  
  237.                 if (pfnWorkerCallBack == null)
  238.                 {
  239.  
  240.                     pfnWorkerCallBack = new AsyncCallback(OnDataReceived);
  241.                 }
  242.  
  243.                StateObject state = new StateObject();
  244.                 state.workSocket = soc;
  245.  
  246.                 soc.BeginReceive(state.buffer, 0, StateObject.BufferSize, SocketFlags.None, pfnWorkerCallBack, state);
  247.  
  248.  
  249.             }
  250.             catch (Exception e1)
  251.             {
  252.             }
  253.  
  254.         }
  255.         public void OnDataReceived(IAsyncResult asyn)
  256.         {
  257.               MyCon = new SqlConnection(this.Conn);
  258.  
  259.             try
  260.             {
  261.                 Console.WriteLine("\n");
  262.                 Console.WriteLine("OnDataRecd");
  263.                 Console.WriteLine("\n");
  264.  
  265.                 StateObject stateobject = (StateObject)asyn.AsyncState;
  266.                 Socket sock = stateobject.workSocket;
  267.  
  268.                 //assgning the app socket to new socket
  269.                Object thisLock = new Object();
  270.  
  271.                 string previousString;
  272.                 int nBytesRec = sock.EndReceive(asyn);
  273.                 if (nBytesRec > 0)
  274.                 {
  275.                     string sReceived = System.Text.Encoding.ASCII.GetString(stateobject.buffer, 0, StateObject.BufferSize);
  276.                     sReceived = sReceived.TrimEnd('\0');
  277.                     if (sReceived != null && sReceived != " " && sReceived != "")
  278.                     {
  279.                         {
  280.  
  281.                             {
  282.                   WriteLogMessage(sReceived);
  283.                         byte[] Buffer = new byte[StateObject.BufferSize];
  284.                         stateobject.buffer = Buffer;
  285.                         sock.BeginReceive(stateobject.buffer, 0, StateObject.BufferSize, SocketFlags.None, new AsyncCallback(OnDataReceived), stateobject);            }
  286.  
  287.                 }
  288.                 else
  289.                 {
  290.                     sock.Disconnect(false);
  291.                     sock.Close();
  292.                     stateobject = null;
  293.                sole.WriteLine("Inside the Else part in ondatareceived");
  294.                                     }
  295.  
  296.             }
  297.  
  298.             catch (SocketException e1)
  299.             {
  300.  
  301.                Console.WriteLine("Inside the catch1 part in ondatareceived");
  302.             }
  303.  
  304.            catch (Exception e1)
  305.             {
  306.            Console.WriteLine("Inside the Catch2 part in ondatareceived");
  307.             }
  308.         }
  309.  

Any help will be appreciated.

Regards
cmrhema
Aug 12 '08 #1
2 1680
Plater
7,872 Recognized Expert Expert
I've not had trouble with any data loss when logging at high speeds.
I DO however see that you are not doing anything in the catch section of the try/catch for your logging. I would guess errors are being thrown.
I would also guess that sine you use async connections, that multiple connections are attempting to log at once and it is throwing exceptions. Try putting some code in to check for exceptions in your writelog function. I bet you will get a better idea of what is happening.
Aug 12 '08 #2
cmrhema
375 Contributor
I've not had trouble with any data loss when logging at high speeds.
I DO however see that you are not doing anything in the catch section of the try/catch for your logging. I would guess errors are being thrown.
I would also guess that sine you use async connections, that multiple connections are attempting to log at once and it is throwing exceptions. Try putting some code in to check for exceptions in your writelog function. I bet you will get a better idea of what is happening.
We have done it, but we did another thing too, instead of writing in a log file, we write into a queue,
It writes up everything without any data loss.
But when we write up in a log file we face data loss.

As of now we decided to put up in a queue first and then read the data from it.

Any suggestions other than that.

Many thanks for the reply Plater.

Regards
cmrhema
Aug 13 '08 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

6
16604
by: Tony C | last post by:
Does Python have a function that is analogous to C's write() or fwrite()- that is , I want to write a file (of arbitrary data) that is 100K, or 1MB (or more) bytes long.. Both write() and fwrite() in C allow the user to specify the size of the data to be written. Python's write only allows a string to be passed in.
4
3481
by: Jon Hyland | last post by:
Hi all, I'm looking for the fastest way to write (and/or read) binary to a file in VC++. I've been using the fstream object in this way: //unsigned char *pDataOut and long iLength initilized somewhere.. fstream file_out((const char *)pszOutFile, ios::in|ios::trunc|ios::binary);
12
2300
by: Christian Blackburn | last post by:
Hi Gang, I would like to know how to write a single bit to a file (if that's possible). I would like to repetitiously write a 1 or 0 as the data I'm trying to save would dictate. Thanks in Advance for an example or explanation, Christian Blackburn
1
2705
by: tim | last post by:
I have a multi-dimensional byte array, private someArray(,,) as byte and it's huge redim someArray(100,640,480,3) after populating the array, I write it to a text file to save it. (so I don't run out of memory). I will retrieve from the file later. What I do is use streamwriter.write and streamreader.read
5
4252
by: Eric Cadwell | last post by:
Is there a faster way to write the last 100K of a large file? This code takes almost two minutes to run on my machine. int buffer = 100000; int length = 2000000000; string file = @"C:\test.txt"; if (File.Exists(file)) File.Delete(file);
12
5460
by: Sean Davis | last post by:
I am working on a simple script to read from one database (oracle) and write to another (postgresql). I retrieve the data from oracle in chunks and drop the data to postgresql continuously. The author of one of the python database clients mentioned that using one thread to retrieve the data from the oracle database and another to insert the data into postgresql with something like a pipe between the two threads might make sense, keeping...
3
5307
by: golden | last post by:
Hello, I am going to ask a question regarding write and lseek. I will provide code at the end of this, but first some background. I am trying to identify the cause of some latency in writing to disk. My user claims that performance is much slower on SAN than on local disk. The developer provided me a C++ program that performed a write
23
6219
by: LilacSkin | last post by:
Hi, Currently, I write an signed long long in a file with the fprintf function: signed long long * pData = NULL; unsigned long long k = 0; unsigned long DataAvail = 0 ; pDataRx = (signed long long *) malloc ( sizeof(signed long long ) *
0
852
by: cmrhema | last post by:
Hi, We are receiving huge number of data thro sockets, which we write up in a Message Queue. Thereafter we take all the values from the Queue and write up into the database. However we notice that there is some data loss when we send huge data. We tested out with 1,000,000 records. We recieved these records within 2 minutes, and we wrote all the data from the queue to the database (Kindly note that both are different exe, but both will...
1
1579
by: Mohamed Yousef | last post by:
Hello , let's say , I'm moving large files through network between devices what is the fastest way to do this ? what i came up with :- 1) using regular file operations with an in memory limit of 4MB which when filled written to disk and re-filled again 2) using memory mapped files in the following way , map first 20MB of
0
8367
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
8279
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
8811
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
8703
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
8467
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
7302
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
4291
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2703
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
1591
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.