Archive

Posts Tagged ‘Network Programming’

C#: A multi-threaded UDP server with BackgroundWorker.

January 12th, 2010 Jimmy No comments

The following code shows you how to build a UDP server in C# using the UUdpClient class for the networking and BackgroundWorker class for reporting data back to the application. This particular UDP server class is designed to be used with a Windows Forms or GUI. When using the UDP server you pass a BackgroundWorker class to the constructor. You should also make sure reporting is enable on that BackgroundWorker class so that they UDP server can report data and error back to your ReportProgress even.

/*
 * Created by Jimmy Burnett (jimmyburnett.com)
 * User: Jim
 * Date: 1/1/2010
 * Time: 9:19 AM
 */
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace JimmyBurnett
{
	public class udpListener
	{
		private System.ComponentModel.BackgroundWorker workerUDP;
		private int port=5121;
		public udpListener(System.ComponentModel.BackgroundWorker workerUDP,int port)
		{
			this.workerUDP = workerUDP;
		}

		/// <summary>
		/// Start the listener.
		/// </summary>
		public void udpListenerStart()
		{
		  try{
			this.workerUDP.ReportProgress(30,"UDP Server Starting...");
			byte[] data = new byte[1024];
			//IPAddress addy = IPAddress.Parse("192.168.1.1");
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, this.port);
            UdpClient newsock = new UdpClient(ipep);
            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
            data = newsock.Receive(ref sender);
				//send a status back to our background worker class.
	        this.workerUDP.ReportProgress(30,"UDP Server Listening...");

			while(true)
            {
             this.workerUDP.ReportProgress(30,"Received Data..");
             this.workerUDP.ReportProgress(50,data.Length);
              data = newsock.Receive(ref sender);
         	}       

         	}catch(Exception ee){
				this.workerUDP.ReportProgress(666,ee.Message);
				Console.WriteLine(ee.Message) ;
     	 	}
	  }
    }
}

Simple Sockets

December 10th, 2009 Jimmy No comments

Simple Sockets is a cross platform socket library. It is different from other socket libraries which mix the application protocol and transport protocol layer (i.e. TCP sockets, UDP sockets, HTTP sockets, etc). This library focuses specifically on the transport protocols. Its features include blocking/non-blocking sockets, polling, thread safety, and signal safety.

This example creates a socket to a time server and receives the time.

#include <string.h>

#include "ActiveSocket.h"       // Include header for active socket object definition

 

int main(int argc, char **argv)

{

    CActiveSocket socket;       // Instantiate active socket object (defaults to TCP).

    char          time[50];

 

    memset(&time, 0, 50);

 

    //--------------------------------------------------------------------------

    // Initialize our socket object 

    //--------------------------------------------------------------------------

    socket.Initialize();

 

    //--------------------------------------------------------------------------

    // Create a connection to the time server so that data can be sent

    // and received.

    //--------------------------------------------------------------------------

    if (socket.Open((const uint8 *)"time-C.timefreq.bldrdoc.gov", 13))

    {

        //----------------------------------------------------------------------

        // Send a requtest the server requesting the current time.

        //----------------------------------------------------------------------

        if (socket.Send((const uint8 *)"\n", 1))

        {

            //------------------------------------------------------------------

            // Receive response from the server.

            //------------------------------------------------------------------

            socket.Receive(49);

            memcpy(&time, socket.GetData(), 49);

            printf("%s\n", time);

 

            //------------------------------------------------------------------

            // Close the connection.

            //------------------------------------------------------------------

            socket.Close();

        }

    }

 

 

    return 1;

}

 

C# TCP/IP Client Server example code.

December 5th, 2009 Jimmy 3 comments

Below is example code written in C# for a TCP/IP client and server. The TCP server uses what is called a Listener object, which listens for incoming connections. On the client side, the code is written to connect to a specific IP address at which point the server side makes a connection and both client and server can talk to each other. If your working in a DLL project in either Mono, Visual Studio or Sharp Develop, you can compiles this into an application library (DLL File).

Server Side Code:

using System;

using System.Net.Sockets;

public class AsynchIOServer

{

public static void Main()

{

TCPListener tcpListener = new TCPListener(10);

tcpListener.Start();

Socket socketForClient = tcpListener.Accept();

if (socketForClient.Connected)

{

Console.WriteLine("Client connected");

NetworkStream networkStream = new NetworkStream(socketForClient);

System.IO.StreamWriter streamWriter =

new System.IO.StreamWriter(networkStream);

System.IO.StreamReader streamReader =

new System.IO.StreamReader(networkStream);

string theString = "Sending";

streamWriter.WriteLine(theString);

Console.WriteLine(theString);

streamWriter.Flush();

theString = streamReader.ReadLine();

Console.WriteLine(theString);

streamReader.Close();

networkStream.Close();

streamWriter.Close();

}

socketForClient.Close();

Console.WriteLine("Exiting...");

}

}

 

Client Code:

using System;

using System.Net.Sockets;

public class Client

{

static public void Main( string[] Args )

{

TCPClient socketForServer;

try

{

socketForServer = new TCPClient("localHost", 10);

}

catch

{

Console.WriteLine(

"Failed to connect to server at {0}:999", "localhost");

return;

}

NetworkStream networkStream = socketForServer.GetStream();

System.IO.StreamReader streamReader =

new System.IO.StreamReader(networkStream);

System.IO.StreamWriter streamWriter =

new System.IO.StreamWriter(networkStream);

try

{

string outputString;

// read the data from the host and display it

{

outputString = streamReader.ReadLine();

Console.WriteLine(outputString);

streamWriter.WriteLine("Client Message");

Console.WriteLine("Client Message");

streamWriter.Flush();

}

}

catch

{

Console.WriteLine("Exception reading from Server");

}

// tidy up

networkStream.Close();

}

}

 

Categories: Programming Tags: ,

How to send email attachments in C#.

December 5th, 2009 Jimmy No comments

attachment-icon-128

.NET provides an easy to use programming framework for developing applications. There are built in classes to do just about anything including email. Emailing with attachments isn’t as hard as you might think. You can email from the local host or an SMTP server with the <strong>SmtpClient</strong> class with just a few lines of code.<!–more–>

To send email attachments in C# you’re going to add some extra namespaces to your project, and then implement the code.

First you will need to add the proper namespaces to your code. You’re going to need the <strong>System.Net</strong>,<strong>System.Net.Mail</strong>, and <strong>System.Net.Mime</strong> namespaces to send attachments using C#. Check out the rest of the code below for a simple example. Keep in mind that this is "short" code and will not compile as is, however this was taken from an application tool I developed.

SmtpClient client = new SmtpClient("mail.smtp.com"); 

MailAddress from = new MailAddress((string) emailAddress); 

MailAddress to = new MailAddress((string) emailAddress);

MailMessage message = new MailMessage(from, to); 

message.Subject = (string) Subject; message.SubjectEncoding = System.Text.Encoding.UTF8; 

Attachment data= new Attachment((string) fileName, MediaTypeNames.Application.Octet); message.Attachments.Add(data); 

message.Body = (string) emailBody; message.BodyEncoding =  System.Text.Encoding.UTF8;