.Net Hive

A blog about Microsoft .Net Platform & other industry happenings

Socket / Network Programming in C#

Today I have decided to give a quick tutorial on Sockets/Network programming in C#. For this I have taken an example of a simple Client/Server application scenario. Where a Socket listen on a specific port and waits for the client to be connected. Once the client is connected, The client application will send a test message to the server application. I will try to achieve this functionality using minimal code and to give a concept of how socket programming works.

Hope this will be helpful. Following is the server application code.

using System;
using System.Text;
using System.Net;
using System.Net.Sockets;

class SocketServer
{
  public static void Main()
  {
    StreamWriter streamWriter;
    StreamReader streamReader;
    NetworkStream networkStream;
    TcpListener tcpListener = new TcpListener(3333);
    tcpListener.Start();
    Console.WriteLine("Server Started. Waiting for Client Connection at port 3333");
    Socket serverSocket = tcpListener.AcceptSocket();
    try
    {
        if (serverSocket.Connected)
        {
            while (true)
            {
                Console.WriteLine("Client Connected at port 3333");
                networkStream = new NetworkStream(serverSocket);
                streamWriter = new StreamWriter(networkStream);
                streamReader = new StreamReader(networkStream);
                Console.WriteLine(streamReader.ReadLine());

            }
        }
        if (serverSocket.Connected)
            serverSocket.Close();
        Console.Read();
    }
    catch (SocketException ex)
    {
        Console.WriteLine(ex);
    }
  }
}

When the above code is executed, it will try to listen on port 3333 and will wait for an incoming connection from a client application. Upon start, server application will display a message “Server Started. Waiting for Client Connection at port 3333”. As soon as the server application recives the connection from client application, it show the message “Client Connected at port 3333”.

Now let’s see how our client application code looks like. Our client application will try to connect at port 3333. Following is the Client Application Code:

using System;
using System.Text;
using System.Net;
using System.Net.Sockets;

class SocketClient
{
  static void Main(string[]args)
  {
    TcpClient tcpClient;
    NetworkStream networkStream;
    StreamReader streamReader;
    StreamWriter streamWriter;
    try
    {
        tcpClient = new TcpClient("localhost", 3333);
        networkStream = tcpClient.GetStream();
        streamReader = new StreamReader(networkStream);
        streamWriter = new StreamWriter(networkStream);
        streamWriter.WriteLine("Client connected at port 3333");
        streamWriter.Flush();
    }
    catch (SocketException ex)
    {
        Console.WriteLine(ex);
    }
    Console.Read();
  }
}

When the above client application code will execute, it will look for an opened connection from a server application at port 3333. As soon as it finds the connection, it will establish the connection with it and will send a message “Client connected at port 3333”. This test message will be displayed on server application console.

A Port is an integer that identifies a process running over a network for the purpose of providing a service. A socket is the end point of a two way communication between two processes running over a network. Microsoft .NET provides excellent support for writing programs that leverage the power of Sockets to implement programs that can run over a network to communicate and share data and information. 

In this entry we tried look at how we can work with Sockets using Microsoft .NET and how we can implement a simple client-server program that can communicate over a network. 

Your comments and suggestions are welcome.

Happy reading!

Waqas Ahmed

Advertisements

Filed under: .Net, Code Snippets, , ,

Data Access with ADO.NET 3.5 – LINQ to SQL

Alright, going back to our series where we discussed LINQ and all related extensions. Lat time we discussed LINQ itself. Today, we are going to talk about LINQ to SQL extension.

Well LINQ to SQL is more than just a LINQ implementation for relational databases; it includes a very easy to use graphical object/relational mapping tool. This tool generates an entity class for each table you select from the SQL Server database to which the project connects. The tool also generates an association that relates to each foreign key constraint. Associations eliminate the need to specify joins in LINQ queries that include projections of fields from related tables. The ability to navigate associations is an important feature of LINQ implementations and the Entity Framework.

The advantage of moving from the relational model of tables, rows, and keys to the entity model of entity classes, entity instances, and associations is that entities usually do represent business objects, such as customers, partners, vendors, employees, products, and services. An entity model enables developers to design real world objects with custom properties, associations, and behaviors suited to the organization’s business processes.

LINQ to SQL is intended for 1:1 mapping of tables:entities, although it does have limited support for entity inheritance of the Table per Hierarchy (TPH) type based on discriminator columns. Read only entities can be based on views or stored procedures. The Entity Framework’s Entity Data Model supports joining multiple tables to create a single updatable entity, as well as several types of entity inheritance.

This entry covers a brief overview about LINQ to SQL extension or you can say a LINQ to SQL in a nutshell. I will try to give some examples about the auto generated classes for entities which entity framework create, in some later post.

Till than, Happy Reading.

Waqas Ahmed

Filed under: .Net, , ,

Language Integrated Query – LINQ

In my previous post, I introduced some of the extensions provided in ADO.NET 3.5 and I told you that we will be talking about each of the extension individually later on.

To start, today I have picked LINQ. Language Integrated Query aka LINQ, is all about achieving query operations in a well comprehensive and open form. It allows you to query data regardless of any type, May it be relational databases, XML or Objects. Considering this phenomenon of querying across any kind of data source, this will be a great breakthrough and major shift in how our programmers deal with data related tasks. Having the possibility at your fingertip to query any kind of data will really change the way we program.

LINQ provides a set of patterns for querying any kind of data, whether it has a particular object model implemented or not. LINQ specifies how an object can be a “queryable,” with all the basic query operations needed, like: SELECT, WHERE, GROUP BY, ORDER BY, JOIN along with many other new operations like SelectMany, GroupJoin, TakeWhile, SkipWhile, ElementAt etc.

The syntax is the part where the real ease and flexibility shows up. You can have any language, that is supported on .Net Platform;  to be able to support LINQ.  C# and VB.NET has this built in features to interfacing LINQ. An example, where you have an array of Employees objects and you want a name of an employees having salary greater then 10000, you can write this query that looks like this:

var query_results =  from c in Employees
                                           let sal = 10000
                                           where c.Salary < sal
                                           select c.Name;

foreach (var result in query_results)
{
          Response.Write(result.ToString());
}

The above example mimics a scenario for a relational database. What happens if we have a dynamic data source like an RSS feed? Here is the simple example for that

XElement orders = …;
int order_amount = Convert.ToInt32(orders.Element(“amount”));

As you have seen that, LINQ is a way to go for data related operations due its flexibility and its data source independence. I have tried to give you an overview of LINQ but there are whole lot of information and resources available for you to get your hands dirty in LINQ :). I’m including some of the references below for your help:

Happy Reading

Waqas Ahmed

Filed under: .Net, , , ,

Microsoft Axum – Parallel Programming Language

Axum is an incubation project from Microsoft’s Parallel Computing Platform that aims to validate a safe and productive parallel programming model for the .NET framework.

It’s a language that builds upon the architecture of the web and the principles of isolation, actors, and message-passing to increase application safety, responsiveness, scalability and developer productivity. Other advanced concepts we are exploring are data flow networks, asynchronous methods, and type annotations for taming side-effects. 

You can get Microsoft Axum from http://www.microsoft.com/downloads/details.aspx?FamilyID=CFE70D5D-37AA-4C4C-8EEB-D4576C41BAA2&displaylang=en

Waqas Ahmed

Filed under: .Net, , , ,

Microsoft “Acropolis”

The Microsoft code name “Acropolis” Community Technology Preview 1 is a set of components and tools that make it easier for developers to build and manage modular, business focused, client .NET applications. Acropolis is part of the “.NET Client Futures” wave of releases, our preview of upcoming technologies for Windows client development.Acropolis builds on the rich capabilities of Microsoft Windows and the .NET Framework, including Windows Presentation Foundation (WPF), by providing tools and pre-built components that help developers quickly assemble applications from loosely-coupled parts and services. With Acropolis you will be able to:

  • Quickly create WPF enabled user experiences for your client applications.
  • Build client applications from reusable, connectable, modules that allow you to easily create complex, business-focused applications in less time.
  • Integrate and host your modules in applications such as Microsoft Office, or quickly build stand-alone client interfaces.
  • Change the look and feel of your application quickly using built-in themes, or custom designs using XAML.
  • Add features such as workflow navigation and user-specific views with minimal coding.
  • Manage, update, and deploy your application modules quickly and easily.

Official Home: http://windowsclient.net/Acropolis

CTP 1 is now available for Acropolis. Do check it out 🙂

Waqas Ahmed

Filed under: .Net, , ,

Pages

Categories

Archives

.Net Hive @ Twitter

Blog Directory by Blog Flux
Computers/Tech blogs