Click here to Skip to main content
15,892,737 members
Articles / Programming Languages / C#
Article

Wireless Push

Rate me:
Please Sign up or sign in to vote.
3.67/5 (8 votes)
24 Sep 2008CPOL2 min read 32.7K   1.3K   34   7
Push files from PC to PDA using C#
wirelesspush_ad.jpg

Introduction  

This article was published on my website on 2nd September, 2008. I put it here in order to let more people read it. I welcome any suggestions and questions. 

Problem: I listen to music while I am driving. I plug my MP3 player into my car, and enjoy whatever it has in there. The memory is not big enough, so that I have to reload some new music once in a while. It bothers me because I have to remind myself to take the player into my room, and take it back to my car. I need a new solution to make my life easier. 

Solution: Using wireless - I have a PDA with built-in GPS, so I keep it in my car all the time in case I cannot find my way home. It runs Windows Mobile 5.0, and has .NET 2.0 Framework, and a wireless card as well. I wrote two pieces of applications in C#. One is the Server running on my PDA, the other is the Client running on my desktop in my room.  

Using the Code

How It Works

I drive home, and park my car outside the house. I connect to my wireless router (no internet needed) using PDA's wireless card. I will get an IP address (normally, I set it static as default). I start my Server program on the PDA, ready to listen to the connection. I turn off other applications and darken the screen to save power. I lock my car, and go into my room. Then I run the Client program on my desktop, specify the server IP (usually it sets as default). I choose a folder where I want my music to be pushed. I press "Start to send" to begin the job.

Screenshots

PShot000.JPG

Server on PDA: Connect to the wireless router (LAN).

PShot002.JPG

Server on PDA: Open the server program.

PShot003.JPG

Server on PDA: Start the server to listen for connections.

PShot004.JPG

Server on PDA: Got the files.

PShot005.JPG

Server on PDA: Good, new music is in the folder.

4.jpg

Here is the music you want to push to the device:

1.jpg

Client on PC: Start the Client program, and specify the Server IP.

2.jpg

Client on PC: Choose the folder where the music is, and Start to Send.

3.jpg

Client on PC: All done!

Source Code

C#
// author: sunny sun
// website: www.sunnyspeed.com
// date: September, 2008
// Client on PC with GUI

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;

namespace Client_GUI
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Client_GUI.sendingPath = "";
            Client_GUI.receiverIP = textBox1.Text;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (Client_GUI.sendingPath.Length > 0)
            {
                Client_GUI.receiverIP = textBox1.Text;
                button1.Enabled = false;
                button2.Enabled = false;
                textBox1.Enabled = false;
                backgroundWorker1.RunWorkerAsync();
            }
            else
                MessageBox.Show("Please select file sending path");
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            label5.Text = Client_GUI.sendingPath;
            label3.Text = Client_GUI.curMsg;
        }

        Client_GUI obj = new Client_GUI();
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            obj.StartSend();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fd = new FolderBrowserDialog();
            if (fd.ShowDialog() == DialogResult.OK)
            {
                Client_GUI.sendingPath = fd.SelectedPath;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }

    //FILE TRANSFER USING C#.NET SOCKET - SERVER
    class Client_GUI
    {
        TcpClient tcpClient;
        static NetworkStream nStream;
        static StreamWriter writeImageData;

        static string Base64ImageData;
        static string BlockData;
        static int RemainingStringLength = 0;
        static string fileName; // include the path and file name

        public Client_GUI()
        {
            
        }

        public static string sendingPath;
        public static string curMsg = "IDLE...";
        public static string receiverIP;

        public void StartSend()
        {
            // that's the IP you want to connect to, and any number for the port
            tcpClient = new TcpClient(receiverIP, 5657); 
            nStream = tcpClient.GetStream();
            writeImageData = new StreamWriter(nStream);

            try
            {
                string[] filePaths = Directory.GetFiles(sendingPath);
                byte[] ImageData;

                foreach (string i in filePaths) // get all files in a directory
                {
                    fileName = i;
                    string fn = i.Substring(i.LastIndexOf('\\') + 1);
                    // send the file name over first
                    // just the file name, not the file path
		  writeImageData.WriteLine(fn); 

                    writeImageData.Flush();
                    //curMsg = "Sent file name: " + fn; //too fast to be seen

                    //start sending the file content
                    FileStream fs = File.OpenRead(fileName);
                    ImageData = new byte[fs.Length];
                    fs.Read(ImageData, 0, ImageData.Length);

                    Base64ImageData = Convert.ToBase64String(ImageData);

                    int bufferSize = 100;   // up to you
                    int ttl = Base64ImageData.Length / bufferSize;
                    RemainingStringLength = Base64ImageData.Length - ttl * bufferSize;

                    //curMsg = "Transferring " + fn;

                    for (int offset = 0; offset <= ttl; offset++)
                    {
                        if (offset < ttl)
                        {
                            BlockData = Base64ImageData.Substring
					(offset * bufferSize, bufferSize);
                        }
                        // deal with the last chunk of data, if there is any left
		      else if (offset == ttl && RemainingStringLength != 0)   
                        {
                            BlockData = Base64ImageData.Substring
				(offset * bufferSize, RemainingStringLength);
                        }
                        else
                        {
                            break;
                        }
                        writeImageData.WriteLine(BlockData);
                        writeImageData.Flush();
                        curMsg = "Transferring \"" + fn + "\"    " + 
				(offset * 100 / ttl) + " %";
                    }

                    fs.Close();

                    // send a signal to notice the server one file is completed
                    writeImageData.WriteLine("DONE");
                    writeImageData.Flush();

                    //curMsg = "Transfer Complete: " + fn;
                }

                writeImageData.Close();
                nStream.Close();
                tcpClient.Close();
            }
            catch (Exception er)
            {
                curMsg = "Unable to connect to server";
                curMsg = er.Message;
            }

            curMsg = "All done!";
        }
    }
}
C#
// author: sunny sun
// website: www.sunnyspeed.com
// date: September, 2008
// Server running on the PDA

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.Net;
using System.Net.Sockets;
using System.IO;

// this is the server running on my PDA
// listen to the client to connect, and receive the incoming file
namespace Server_pda
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void menuItem1_Click(object sender, EventArgs e)
        {
            Close();    // click "exit" to exit this program
        }

        private void button1_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;

            //string path = ".\\Storage Card\\FromPC\\";  
            // up to you, save into the memory card is way too slow
            //I saved the incoming files in a folder on my PDA
	   string path = ".\\FromPC\\";   

            bool haha = true;

            IPAddress ipAddress = IPAddress.Any;
            TcpListener tcpListener = new TcpListener(ipAddress, 5657);
            tcpListener.Start();
            //label2.Text = "Server started.";

            while (haha)
            {
                TcpClient tcpClient = tcpListener.AcceptTcpClient();
                //label2.Text = "Client connected.";

                NetworkStream nStream = tcpClient.GetStream();
                StreamReader readImageData = new StreamReader(nStream);

                //label2.Text = "Start to receive the file.";

                //receive the first file name first
                string fileName = readImageData.ReadLine();
                // create the first file
	       FileStream fs = new FileStream(path + fileName, FileMode.Create);

                string data;    //received string data
                int counter = 0;    //number of files
                bool moreFile = false;
                byte[] byte_image;  //data to binary file

                while ((data = readImageData.ReadLine()) != null)
                {
                    if (moreFile)
                    {
                        fileName = data;
                        // create the file
                        fs = new FileStream(path + fileName, FileMode.Create); 
		      moreFile = false;
                    }
                    else if (data.Equals("DONE"))    // one file is finished
                    {
                        moreFile = true;
                        counter++;  // count files

                        //clean
                        fs.Flush();
                        fs.Close();
                        nStream.Flush();
                        GC.Collect();
                        GC.WaitForPendingFinalizers();
                    }
                    else
                    {
                        byte_image = Convert.FromBase64String(data.ToString());
                        fs.Write(byte_image, 0, byte_image.Length);
                    }
                }

                readImageData.Close();
                nStream.Close();
                tcpClient.Close();

                if (counter > 1)
                {
                    label2.Text = counter + " files are saved.";
                }
                else
                {
                    label2.Text = counter + " file is saved.";
                }
            }
        }
    }
}	 

Points of Interest

  1. PDA can be turned off automatically after a certain time. However, I let it run all the time, so that I can push music whenever I want to. The standby mode doesn't consume too much power. The PDA can be charged on the go, or charged using solar power.
  2. I can download the PC Client here, so that I can get it anywhere (work, friends' place, etc.), and push new music to my device. NICE!  

History

  • 24th September, 2008: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Canada Canada
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionI need the opposite Pin
Member 1133324326-Dec-14 4:23
Member 1133324326-Dec-14 4:23 
Generalthanks Pin
mbaocha11-Aug-09 23:49
mbaocha11-Aug-09 23:49 
I cant pass by without saying thanks for this article. It was helpful. I'm interested in articles relating to diy wind/solar/electrical energy. i'm an engineer.


_________________________________________________________________
wind solar energy from home | diy home made solar wind energy
GeneralMb/s Pin
zorgan3-Jun-09 11:19
zorgan3-Jun-09 11:19 
JokeHey, what's the meaning of .... Pin
neil young29-Sep-08 5:43
neil young29-Sep-08 5:43 
GeneralRe: Hey, what's the meaning of .... Pin
seesunmoon29-Sep-08 6:18
seesunmoon29-Sep-08 6:18 
GeneralNice app! Pin
Dinesh Mani24-Sep-08 23:57
Dinesh Mani24-Sep-08 23:57 
GeneralRe: Nice app! Pin
seesunmoon29-Sep-08 6:21
seesunmoon29-Sep-08 6:21 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.