Arioo Barzan
Published © GPL3+

Connect Raspberry pi and PC with TCP/IP using Csharp

Connect a Raspberry Pi Model 2|3 B (Windows IoT core) and PC (Wiindows 7,8,10) with TCP/IP protocol using Csharp Network Classes

BeginnerShowcase (no instructions)30 minutes8,520
Connect Raspberry pi and PC with TCP/IP using Csharp

Things used in this project

Story

Read more

Code

Server Side - Raspberry pi

C#
Listen to a port (e.g 8800)
private async void listen()
        {
            try
            {
                //Create a StreamSocketListener to start listening for TCP connections.
                Windows.Networking.Sockets.StreamSocketListener socketListener = new Windows.Networking.Sockets.StreamSocketListener();

                //Hook up an event handler to call when connections are received.
                socketListener.ConnectionReceived += SocketListener_ConnectionReceived;

                //Start listening for incoming TCP connections on the specified port. You can specify any port that' s not currently in use.
                await socketListener.BindServiceNameAsync("8800");
            }
            catch (Exception e)
            {
                if (OnError != null)
                    OnError(e.Message);
            }

        }

Server read from client

C#
private async void SocketListener_ConnectionReceived(Windows.Networking.Sockets.StreamSocketListener sender,
    Windows.Networking.Sockets.StreamSocketListenerConnectionReceivedEventArgs args)
        { 

            StringBuilder request = new StringBuilder();
            byte[] data = new byte[BuffreSize];
            IBuffer buffer = data.AsBuffer();
            StreamSocket socket = args.Socket;
            using (IInputStream input = socket.InputStream)
            {
                buffer = await input.ReadAsync(buffer, BuffreSize, InputStreamOptions.Partial);
                request.Append(Encoding.UTF8.GetString(data, 0, (int)buffer.Length));
            }
        }

Server send data to client

C#
using (var outputStream = socket.OutputStream)
            {
                using (Stream resp = outputStream.AsStreamForWrite())
                {
                    var message = request.ToString()+" sent";
                    byte[] headerArray = Encoding.UTF8.GetBytes(message);
                    await resp.WriteAsync(headerArray, 0, headerArray.Length);
                    await resp.FlushAsync();
                }
            }

Sample Client

C#
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;


public class AsynchronousSocketClient
{
    public static void Main(String[] args)
    {
        Connect("192.168.1.77","Hello World");
    }
    static void Connect(String server, String message)
    {
        try
        {
            // Create a TcpClient.
            // Note, for this client to work you need to have a TcpServer 
            // connected to the same address as specified by the server, port
            // combination.
            Int32 port = 8800;
            TcpClient client = new TcpClient(server, port);

            // Translate the passed message into ASCII and store it as a Byte array.
            Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);

            // Get a client stream for reading and writing.
            //  Stream stream = client.GetStream();

            NetworkStream stream = client.GetStream();

            // Send the message to the connected TcpServer. 
            stream.Write(data, 0, data.Length);

            Console.WriteLine("Sent: {0}", message);

            // Receive the TcpServer.response.

            // Buffer to store the response bytes.
            data = new Byte[1024];

            // String to store the response ASCII representation.
            String responseData = String.Empty;

            // Read the first batch of the TcpServer response bytes.
            Int32 bytes = stream.Read(data, 0, data.Length);
            responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
            Console.WriteLine("Received: {0}", responseData+"0");

            // Close everything.
            stream.Close();
            client.Close();
        }
        catch (ArgumentNullException e)
        {
            Console.WriteLine("ArgumentNullException: {0}", e);
        }
        catch (SocketException e)
        {
            Console.WriteLine("SocketException: {0}", e);
        }

        Console.WriteLine("\n Press Enter to continue...");
        Console.Read();
    }

}

Credits

Arioo Barzan

Arioo Barzan

0 projects • 4 followers
Desktop Programmer Web Developer Mobile Developer Network Programmer Graphic Designer

Comments