C# .NET - Socket.Send and Receive - Asked By Pavan Bhargav on 22-Mar-12 07:58 AM

Earn up to 30 extra points for answering this tough question.
I have written this code to search for a string from a file. Since this program cannot be used for multiple clients, i was asked to make it more robust by using socket. I want to know where and how socket could be used in this program.. I'm still learning about sockets.. Couldn't exactly figure out where and how exactly it could be used.. Could someone just help me with it? I'm supposed to write the server side program.. I've also tried creating a tcp connection.. But i don know how and where exactly to imply my program into the first program.. This is my tcp connection program, followed by my actual program..
class Server
  {
    private TcpListener tcpListener;
    private Thread listenThread;
 
    public Server()
    {
       
      this.tcpListener = new TcpListener(IPAddress.Any, 3000);
      this.listenThread = new Thread(new ThreadStart(ListenForClients));
      this.listenThread.Start();
    }
 
    private void ListenForClients()
    {
      this.tcpListener.Start();
 
      while (true)
      {
        TcpClient client = this.tcpListener.AcceptTcpClient();
        Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
        clientThread.Start(client);
      }
    }
 
 
    private void HandleClientComm(object client)
    {
      TcpClient tcpClient = (TcpClient)client;
      NetworkStream clientStream = tcpClient.GetStream();
 
      byte[] message = new byte[4096];
      int bytesRead;
 
      while (true)
      {
        bytesRead = 0;
 
        try
        {
          bytesRead = clientStream.Read(message, 0, 4096);
        }
        catch
        {
          break;
        }
 
        if (bytesRead == 0)
        {
 
          break;
        }
 
 
       ASCIIEncoding encoder = new ASCIIEncoding();
       System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));
      }
 
      tcpClient.Close();
    }
  }
}
class Program
{
 
  static void Main(string[] args)
  {
    if (File.Exists("C://myfile2.txt"))
    {
      var text = File.ReadAllText("C://myfile2.txt");
 
 
      foreach (var word in new[] { "and", "so", "not", "c", "to", "by", "has", "do", "behavior", "dance", "france", "ok", "thast", "please", "hello", "system", "possible", "impossible", "absolutely", "sachin", "bradman", "schumacher", "http", "console", "application" })
      {
        var w = word;
 
        new Thread(() => Console.WriteLine("{0}: {1}", w, text.Contains(w) ? "Present" : "Not Present")).Start();
      }
 
    }
    else
      Console.WriteLine("File Does not exist");
    Console.ReadLine();
  }
 
}








D Company replied to Pavan Bhargav on 22-Mar-12 09:53 AM
In Socket programming we use send method to  send data from your buffer to a connected Socket. When we call the Send method it returns number of bytes which were sent by the method(in your case it could be a search string ).
 
and  the data were stored in a socket buffer(the search result) and the socket will be trying to send them.

though i have not done practical but have seen good article in MSDN

A complete Example from MSDN

http://msdn.microsoft.com/en-us/library/ms145160.aspx

give a try and let us know in case need  more help on this
D
kalpana aparnathi replied to Pavan Bhargav on 22-Mar-12 02:18 PM
hi,

Use referance link:

http://www.codeproject.com/Articles/2418/Making-Socket-Based-Application-Using-TcpListener

Regards,
Pavan Bhargav replied to kalpana aparnathi on 26-Mar-12 05:15 AM
Hi Kalpana, D..
I tried writing the code and came till here.. But it was through a lot of help.. Not able to get the output.. Could someone help me out? Thanks alot.. 


using System;
using
System.IO;
using
System.Text;
using
System.Text.RegularExpressions;
using
System.Net.Sockets;

class Program
{
   
private static Regex _regex = new Regex("and|so|not|c|to|by|has|do|behavior|dance|france|ok|thast|please|hello|system|possible|impossible|absolutely|sachin|bradman|schumacher|http|console|application", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);

   
static void Main(string[] args)
   
{
       
TcpListener serversocket = new TcpListener(8888);
       
TcpClient clientsocket = default(TcpClient);
        serversocket
.Start();
       
Console.WriteLine(">> Server Started");
        clientsocket
= serversocket.AcceptTcpClient();
       
Console.WriteLine("Accept Connection From Client");

       
try
       
{
            using
(var reader = new StreamReader(clientsocket.GetStream()))
           
{
               
string line;
               
int lineNumber = 0;
               
while (null != (line = reader.ReadLine()))
               
{
                    lineNumber
+= 1;
                   
foreach (Match match in _regex.Matches(line))
                   
{
                       
Console.WriteLine("Line {0} matches {1}", lineNumber, match.Value);
                   
}
               
}
           
}
       
}
       
catch (Exception ex)
       
{
           
Console.Error.WriteLine(ex.ToString());
       
}

        clientsocket
.Close();
        serversocket
.Stop();
       
Console.WriteLine(" >> exit");
       
Console.ReadLine();
   
}