Kunamatata/Raspberry-PI-Server-Client-TCP
Use Git or checkout with SVN using the web URL.
Work fast with our official CLI. Learn more.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Raspberry PI Model 3 B NeoPixels with Server-Client TCP Sockets
This project is a fun experimentation. The initial goal was to move my mouse on my computer and light up an LED Strip connected to my Raspberry Pi.
- The Raspberry PI is the server
- The Computer is the client
More features will be coming soon, this project is for fun. There’s no limit to how you want to play with the LEDs.
- Server receives client input and switches to a mode:
- The LEDS light up according to the the mouse cursor position on the Y-Axis. If your mouse is on the right most side of the screen, all LEDs are on. If it’s on the left all leds are off. It’s progressive transition
- Client sends data to the server
- Addressable RGB LED Strip, 5V. With either SK6812 or WS2812B-based LEDs
- Raspberry PI Model 3
The server is the only one to have external dependencies to be able to run.
- Server:
- Run the following your command line: sudo pip3 install rpi_ws281x adafruit-circuitpython-neopixel
About
Control LEDs conneccted to your RPI remotely from your computer through TCP Sockets
Mad-Scientist-Monkey/sockets-ccpp-rpi
Use Git or checkout with SVN using the web URL.
Work fast with our official CLI. Learn more.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Sockets in C/C++ for Raspberry Pi
This is a quick tutorial on socket programming in C/C++ on a Raspbian Raspberry Pi, based on Socket programming in C on Linux – tutorial. I complemented with a part for Raspbian OS, and some changes more likely to my personal taste.
- Sockets are the «virtual» endpoints of any kind of network communications done between 2 hosts over in a network.
- All along the tutorial there are code snippets to demonstrate some concepts. You can run those code snippets in geany rightaway and test the results to better understand the concepts.
A client is an application that connects to a remote system to fetch or retrieve data. In this case, the steps to run such activities are
- Create a socket
- Connect to remote server
- Send some data
- Receive a reply
Create a socket
This first thing to do is create a socket. The socket function does this. For example,
The function socket() creates a socket and returns a descriptor which will be used by other functions. The above code will create a socket with the following properties:
- Address family : AF_INET (this is IPV4)
- Type : SOCK_STREAM (this means connection oriented to TCP protocol)
- Protocol — 0 : or IPPROTO_IP, this is IP protocol
Quick note: Apart from SOCK_STREAM type of sockets there is another type called SOCK_DGRAM which indicates the UDP protocol. This type of socket is non-connection socket. In this tutorial we shall stick to SOCK_STREAM or TCP sockets.
Connect Socket to a Server
We connect to a remote server on a certain port number, so we need the IP address and port number to connect to.
To connect to a remote server we need to do a couple of things. First is to create a sockaddr_in structure with proper values.
So take a look in the following structures. In this case, the sockaddr_in has a member called sin_addr of type in_addr which has a s_addr which is nothing but a long. It contains the IP address in long format.
Function inet_addr is a very handy function to convert an IP address to a long format. This is how you do it :
So you need to know the IP address of the remote server you are connecting to. Here we used the ip address of google.com as a sample. Appendix 1 section shows how to find out the ip address of a given domain name.
The last thing needed is the connect function. It needs a socket and a sockaddr structure to connect to. Here is a code sample.
It cannot be any simpler. It creates a socket and then connects. If you run the program it should show Connected. Try connecting to a port different from port 80 and you should not be able to connect which indicates that the port is not open for connection.
So we are now connected. The next step is to send some data to the remote server.
Note : Connections are present only in tcp sockets : The concept of «connections» apply to SOCK_STREAM/TCP type of sockets. Connection means a reliable «stream» of data such that there can be multiple such streams each having communication of its own. Think of this as a pipe which is not interfered by other data.
Other sockets like UDP , ICMP , ARP dont have a concept of «connection». These are non-connection based communication. Which means you keep sending or receiving packets from anybody and everybody.
Send data over socket
Function send will simply send data. It needs the socket descriptor, the data to send and its size. Here is a very simple example of sending some data to google.com IP :
In the above example , we first connect to an IP address and then send the string message «GET / HTTP/1.1\r\n\r\n» to it. The message is actually a http command to fetch the mainpage of a website.
When sending data to a socket you are basically writing data to that socket. This is similar to writing data to a file. Hence you can also use the write function to send data to a socket. Later in this tutorial we shall use write function to send data.
Now that we have sent some data, it’s time to receive a reply from the server.
Receive data from socket
Function recv is used to receive data from a socket. In the following example we shall send the same message as the last example and receive a reply from the server.
Here is the output of the above code :
302 Moved
We can see what reply was send by the server. It looks something like Html, well IT IS html. Google.com replied with the content of the page we requested. Quite simple!
Note : When receiving data on a socket , we are basically reading the data on the socket. This is similar to reading data from a file. So we can also use the read function to read data on a socket. For example :
Now that we have received our reply, its time to close the socket.
Function close is used to close the socket. Need to include the unistd.h header file for this.
The other kind of socket application is called a socket server. A server is a system that uses sockets to receive incoming connections and provide them with data. Servers are the opposite of clients, that instead of connecting out to others, they wait for incoming connections. So www.google.com is a server and your web browser is a client. Or more technically www.google.com is a HTTP Server and your web browser is an HTTP client.
Socket servers operate in the following manner
- Open a socket
- Bind to a address(and port)
- Listen for incoming connections
- Accept connections
- Read/Send data
We have already learnt how to open a socket. So the next thing would be to bind it.
Bind socket to a port
The bind function can be used to bind a socket to a particular «address and port» combination. It needs a sockaddr_in structure similar to connect function.
Now that bind is done, its time to make the socket listen to connections. We bind a socket to a particular IP address and a certain port number. By doing this we ensure that all incoming data which is directed towards this port number is received by this application.
This makes it obvious that you cannot have 2 sockets bound to the same port.
Listen for incoming connections on the socket
After binding a socket to a port the next thing we need to do is listen for connections. For this we need to put the socket in listening mode. Function listen is used to put the socket in listening mode. Just add the following line after bind.
Now comes the main part of accepting new connections.
Function accept is used for this. Here is the code
Program output : running the program, it should show
So now this program is waiting for incoming connections on port 8888. Dont close this program, keep it running. Now a client can connect to it on this port. We shall use the telnet client for testing this. Open a terminal and type $ telnet localhost 8888 .
On the terminal you shall get
And the server output will show
So we can see that the client connected to the server. Try the above process till you get it perfect.
Get the ip address of the connected client
You can get the ip address of client and the port of connection by using the sockaddr_in structure passed to accept function. It is very simple :
We accepted an incoming connection but closed it immediately. This was not very productive. There are lots of things that can be done after an incoming connection is established. Afterall the connection was established for the purpose of communication. So lets reply to the client.
We can simply use the write function to write something to the socket of the incoming connection and the client should see it. Here is an example.
Run the above code in 1 terminal. And connect to this server using telnet from another terminal and you should see this :
So the client(telnet) received a reply from server.
We can see that the connection is closed immediately after that simply because the server program ends after accepting and sending reply. A server like www.google.com is always up to accept incoming connections.
It means that a server is supposed to be running all the time. Afterall its a server meant to serve. So we need to keep our server RUNNING non-stop. The simplest way to do this is to put the accept in a loop so that it can receive incoming connections all the time.
So a live server will be alive for all time. Lets code this up :
We havent done a lot there. Just the accept was put in a loop.
Now run the program in 1 terminal, and open 3 other terminals. From each of the 3 terminal do a telnet to the server port.
Each of the telnet terminal would show :
And the server terminal would show
So now the server is running nonstop and the telnet terminals are also connected nonstop. Now close the server program. All telnet terminals would show Connection closed by foreign host . Good so far. But still there is not effective communication between the server and the client.
The server program accepts connections in a loop and just send them a reply, after that it does nothing with them. Also it is not able to handle more than 1 connection at a time. So now its time to handle the connections, and handle multiple connections together.
Handling multiple socket connections with threads
To handle every connection we need a separate handling code to run along with the main server accepting connections. One way to achieve this is using threads. The main server program accepts a connection and creates a new thread to handle communication for the connection, and then the server goes back to accept more connections.
On Linux threading can be done with the pthread (posix threads) library. From Raspberry Pi Raspbian OS you may probably have to install PThreads library with
We shall now use threads to create handlers for each connection the server accepts.
Run the above server and open 3 terminals like before. Now the server will create a thread for each client connecting to it.
This one looks good , but the communication handler is also quite dumb. After the greeting it terminates. It should stay alive and keep communicating with the client.
One way to do this is by making the connection handler wait for some message from a client as long as the client is connected. If the client disconnects , the connection handler ends.
So the connection handler can be rewritten like this :
The above connection handler takes some input from the client and replies back with the same. Simple! Here is how the telnet output might look
So now we have a server thats communicative. Thats useful now.
Linking the pthread library
When compiling programs that use the pthread library you need to link the library. This is done like this :
When connecting to a remote host, it is necessary to have its IP address. Function gethostbyname is used for this purpose. It takes the domain name as the parameter and returns a structure of type hostent . This structure has the IP information. It is present in netdb.h . Lets have a look at this structure.
The h_addr_list has the IP addresses. So now lets have some code to use them.
Output of the code would look like :
So the above code can be used to find the IP address of any domain name. Then the IP address can be used to make a connection using a socket.
Function inet_ntoa will convert an IP address in long format to dotted format. This is just the opposite of inet_addr .
So far we have see some important structures that are used. Lets revise them :
- sockaddr_in — Connection information. Used by connect , send , recv etc.
- in_addr — IP address in long format
- sockaddr
- hostent — The IP addresses of a hostname. Used by gethostbyname
An usefull function to get the IP of a generic domain host first address is