Click here to Skip to main content
15,885,890 members
Articles / Internet of Things / Raspberry-Pi

Simple Connection Between Raspberry Pi 2 with Windows 10 IoT to PC using C#

Rate me:
Please Sign up or sign in to vote.
4.14/5 (5 votes)
8 Mar 2016CPOL2 min read 58.8K   1.4K   25   19
This project will show how send a simple string between Raspberry Pi 2 with Windows 10 IoT and PC using C# over networking TCP/IP, where Raspberry is a server and PC is the client.

Introduction

This project will show you how to send a simple string between Raspberry Pi 2 with Windows 10 IoT and PC with Windows 10 using C# and UWP(Universal Windows Platform) over TCP/IP network, where Raspberry is a server and PC is a client and PC sends a message to Raspberry.

Background

UWP - Universal Windows Platform

UWP is a new type of project from Microsoft which allows applications to run in any Windows platform (like Windows 8 or superior, Xbox, Windows phone, etc.) without any modification, and now you have a “Manifest”, if you don't give permission in manifest, your app won't work. For further information, access this link:

Windows 10 IoT Core

Windows 10 IoT Core is a version of Windows 10 that is optimized for small devices with or without display. When this article was written, Windows 10 IoT Core supported the following devices:

  • Raspberry Pi 2
  • Arrow DragonBoard 410c
  • MinnowBoard MAX.

You can use UWP to develop apps for Windows 10 IoT Core. For more information, access this link:

Project

For this project, one “Solution” with two projects were created, one using UWP(client) and the other using Background IoT(Server). To access the entire project, access this link:

Diagram

Image 1

Receiving String (Server)

Here, I’m going to show how to bind some port and wait for a connection. For that, a SocketServer class was made.

Variables

C#
private readonly int _port;
public int Port { get { return _port; } }

private StreamSocketListener listener;

public delegate void DataRecived(string data);
public event DataRecived OnDataRecived;


public delegate void Error(string message);
public event Error OnError;

Bind Port

C#
public async void Star() 
{ 
    listener = new StreamSocketListener(); 
    listener.ConnectionReceived += Listener_ConnectionReceived; 
    await listener.BindServiceNameAsync(Port.ToString()); 
}

Wait Receive Message

C#
private async void Listener_ConnectionReceived
(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{ 
    var reader = new DataReader(args.Socket.InputStream); 
    try 
    { 
        while (true) 
        { 
            uint sizeFieldCount = await reader.LoadAsync(sizeof(uint)); 
            //if disconnected 
            if (sizeFieldCount != sizeof(uint)) 
                return; 
            uint stringLenght = reader.ReadUInt32(); 
            uint actualStringLength = await reader.LoadAsync(stringLenght); 
            //if disconnected 
            if (stringLenght != actualStringLength) 
                return; 
            if (OnDataRecived != null) 
                OnDataRecived(reader.ReadString(actualStringLength)); 
            } 
    } 
    catch (Exception ex) 
    { 
        if (OnError != null) 
            OnError(ex.Message); 
    } 
}

Start Application

C#
public void Run(IBackgroundTaskInstance taskInstance)
{
    ...
    taskInstance.GetDeferral();
    var socket = new SocketServer(9000);
    ThreadPool.RunAsync(x => {
        socket.Star();
        socket.OnError += socket_OnError;
        socket.OnDataRecived += Socket_OnDataRecived;
    });
}  

And don't forget to give the app the ability to be client and server, see the image below:

Image 2

Send String (Client)

The client was tested in Windows 10 with UWP. To send strings, it created a SocketClient class:

Variable

C#
private readonly string _ip;
private readonly int _port;
private StreamSocket _socket;
private DataWriter _writer;
private DataReader _reader;

public delegate void Error(string message);
public event Error OnError;

public delegate void DataRecived(string data);
public event DataRecived OnDataRecived;

public string Ip { get { return _ip; } }
public int Port { get { return _port; } }

Connect

For creating a connection, you need this code:

C#
public async void Connect()
{
    try
    {
        var hostName = new HostName(Ip);
        _socket = new StreamSocket();
        await _socket.ConnectAsync(hostName, Port.ToString());
        _writer = new DataWriter(_socket.OutputStream);
        Read();
    }
    catch (Exception ex)
    {
        ..
    }
}

Send String

C#
public async void Send(string message)
{
    _writer.WriteUInt32(_writer.MeasureString(message));
    _writer.WriteString(message);

    try
    {
        await _writer.StoreAsync();
        await _writer.FlushAsync();
    }
    catch (Exception ex)
    {
        ...
    }
}

Read

To read something, the code is the same code used in class ServerSocket.

Close

C#
public void Close()
{
    _writer.DetachStream();
    _writer.Dispose();

    _reader.DetachStream();
    _reader.Dispose();

    _socket.Dispose();
}

Conclusion

To create a simple connection to send a string, you don't need a complex or a large code, and it's simple to use C# with UWP, and now it’s possible to grow some application and create something more complex. UWP is good, but you have many things to learn, because it's a new framework and it introduces a new concept about design and development, since most methods will be async.

Acknowledgements

I would like to thank my two friends, Guilherme Effenberger and Ricardo Petrére, for helping me to write and translate this text.

License

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


Written By
Software Developer Toledo do Brasil
Brazil Brazil
Formed in analysis and development of system by FTT, currently working with C # and AspNet. At home I study development Raspberry Pi 2, Android(Android studio and Xamarin), UWP, Qt. I have an interest in IoT, Cloud, Machine Learning and Big Data.

Comments and Discussions

 
Question2 UWP app one server - one client Pin
Member 1313466929-Sep-18 1:16
Member 1313466929-Sep-18 1:16 
QuestionImplement authentication to server Pin
Dipti Mamidala28-Dec-17 21:27
Dipti Mamidala28-Dec-17 21:27 
Questionerror "exception not managed.." Pin
Member 1307737427-Mar-17 6:49
Member 1307737427-Mar-17 6:49 
AnswerRe: error "exception not managed.." Pin
Rafael Lillo23-Aug-17 13:36
professionalRafael Lillo23-Aug-17 13:36 
QuestionPI as client, PC as server Pin
Richie Lo7-Jul-16 0:13
Richie Lo7-Jul-16 0:13 
AnswerRe: PI as client, PC as server Pin
Rafael Lillo7-Jul-16 16:39
professionalRafael Lillo7-Jul-16 16:39 
QuestionI am christopher Pin
Member 12499146(Christopher)4-May-16 21:26
Member 12499146(Christopher)4-May-16 21:26 
AnswerRe: I am christopher Pin
Rafael Lillo9-May-16 0:13
professionalRafael Lillo9-May-16 0:13 
QuestionThank you and hello man Pin
Member 12499146(Christopher)3-May-16 17:11
Member 12499146(Christopher)3-May-16 17:11 
QuestionThanks Pin
Member 1193038710-Mar-16 18:35
Member 1193038710-Mar-16 18:35 
AnswerRe: Thanks Pin
Rafael Lillo12-Mar-16 8:20
professionalRafael Lillo12-Mar-16 8:20 
QuestionTesting Pin
Member 119303879-Mar-16 19:06
Member 119303879-Mar-16 19:06 
AnswerRe: Testing Pin
Rafael Lillo10-Mar-16 13:24
professionalRafael Lillo10-Mar-16 13:24 
QuestionThanks very much Pin
Member 119303878-Mar-16 18:44
Member 119303878-Mar-16 18:44 
QuestionZip file Pin
Member 119303877-Mar-16 18:11
Member 119303877-Mar-16 18:11 
GeneralRe: Zip file Pin
Rafael Lillo8-Mar-16 12:23
professionalRafael Lillo8-Mar-16 12:23 
Questionzip file Pin
Member 119303874-Mar-16 15:52
Member 119303874-Mar-16 15:52 
QuestionZip download Pin
Member 119303873-Mar-16 18:54
Member 119303873-Mar-16 18:54 
AnswerRe: Zip download Pin
Rafael Lillo4-Mar-16 5:02
professionalRafael Lillo4-Mar-16 5:02 

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.