I'm new to C and for a homework exam I must implement a simple server socket program which sends some data in a loop and if the client is connected to the server socket(have done it with Arduino but need the same functionallity on raspberrypi or other sbc).
For example (arduino style):
EthernetServer server = EthernetServer(23);
// start listening for clients
server.begin();
int i = 0;
while(true){
i++;
EthernetClient client = server.available();
if (client) {
while (client.connected()) {
if (client.available()) {
client.print(i);
}
}
}
client.stop;
}
I have a SBC (single board computer) with GPIO buss. My program must:
read values from SPI bus (infinite loop)
if the client is connected to the server scoket It must send some values to the client.
I know how to implement this kind of app in Java but in C, I don't have enaugh knowledge.
I'am looking for some kind of library or example on how to implement it.
regards
You can refer below mentioned link to establish a client/server connection using sockets with RPi with C implementation. Hope it helps you.
http://cs.smith.edu/dftwiki/index.php/Tutorial:_Client/Server_on_the_Raspberry_Pi
Related
I want to connect two F746ZG boards so that they can communicate via TCP. I am using the STM implementation of LwIP with the netconn API. The IP address is supplied via DHCP, but it is always the same address. Also, the address matches the expected value. The problem I am facing is that the client seemingly can't establish a connection. I am binding the connection to port 8880. Since I ran into this issue, I have written a debug client that should just periodically send a predefined message to a server. Here is the code for the client:
static void tcpecho_client_thread(void const *arg)
{
struct netconn *xNetConn = NULL;
err_t bind_err, connect_err;
char* b_data = "OK"; // Data to be sent
uint16_t b_len = sizeof ( b_data );
IP4_ADDR(&local_ip, IP_ADDR0_CLIENT, IP_ADDR1_CLIENT, IP_ADDR2_CLIENT, IP_ADDR3_CLIENT);
IP4_ADDR(&pc_ip, IP_ADDR0_PC, IP_ADDR0_PC, IP_ADDR2_PC, IP_ADDR3_PC);
xNetConn = netconn_new ( NETCONN_TCP );
if (xNetConn != NULL){
bind_err = netconn_bind ( xNetConn, &local_ip, TCP_PORT_NETCONN );
if(bind_err == ERR_OK){
// Try to connect to server
for(;;){
connect_err = netconn_connect ( xNetConn, &pc_ip, TCP_PORT_NETCONN);
if (connect_err == ERR_OK){
// We are connected
while(1){
BSP_LED_On(LED1);
netconn_write(xNetConn, b_data, b_len, NETCONN_COPY);
vTaskDelay(1000); // To see the result easily in Comm Operator
}
}
}
}else{
// Failed to bind the connection
BSP_LED_On(LED3);
}
}else{
// Failed to allocate a new connection
BSP_LED_On(LED3);
}
}
When I debug this, netconn_connect never manages to actually connect to something. Since I am able to ping the board and get a response, I am confused, what is going wrong here. I have tried to use Hercules to set up a TCP server on my PC so that the board can connect to that, but that also doesn't work. Using Wireshark, I can see the responses to my ping command coming in, but I don't see anything that would indicate the board trying to connect to my PC.
I have tested the corresponding server on the second board, but that runs fine. I can connect to it with Hercules and send data, so I doubt there is anything fundamentally wrong with the LwIP stack.
What I could guess is that I messed up the netconn_bind, I am not 100% sure what IP you are supposed to bind the connection to. The way it currently is, is how I read the documentation. For the server, I have bound it to IP_ADDR_ANY. Besides that, my implementation mostly matches with the examples you can find online (e.g. LwIP Wiki).
I have figured out the problem. After I delete the netconn_bind call, everything works fine for me.
I'm using the Eclipse Paho MQTT C client to connect to a mosquitto broker with TLS using openssl. This is part of my code:
MQTTClient client;
MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
MQTTClient_message pubmsg = MQTTClient_message_initializer;
MQTTClient_SSLOptions sslOptions = MQTTClient_SSLOptions_initializer;
MQTTClient_deliveryToken token;
int rc;
MQTTClient_create(&client, ADDRESS, CLIENTID,
MQTTCLIENT_PERSISTENCE_NONE, NULL);
conn_opts.keepAliveInterval = 20;
conn_opts.cleansession = 1;
/* TLS */
sslOptions.enableServerCertAuth = 0;
sslOptions.trustStore = "ca_rsp.crt";
conn_opts.ssl = &sslOptions;
if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
{
printf("Failed to connect, return code %d\n", rc);
exit(EXIT_FAILURE);
}
Actually every time I reconnect to the broker, the client make a full handshake. I would like to use the TLS session resumption to reduce the overhead. I've search around the web but I haven't found any example of how o implement that in a simple way.
Any suggestion?
Thanks
This came up recently on the mosquitto dev mailing list here https://dev.eclipse.org/mhonarc/lists/mosquitto-dev/msg01606.html
The following excerpt seams to imply it may not be possible just yet with the code as it is.
How can I use Mosquitto / OpenSSL C API to leverage session tickets in an
MQTT C client ?
Not at the moment, this needs code changes that are a bit more
involved - it looks like we need to use SSL_set_session() to apply a
saved session to your client and SSL_CTX_sess_set_new_cb() to save the
session out.
Is there any way I could persist session tickets on the clients, so they
would remain valid across reboot ?
With the above changes, yes.
Make conn_opts.cleansession = 0;
Disabling the cleansession flag in PAHO-client programs enables session resumption.
I have already verified it with wireshark.
With session Resumption, 1st packet transmission
We can see 4 times communication between server and client in 1 image and even certificates are transferred.
With session Resumption ,screenshot taken for 2nd packet transmission
Observe both images carefully , there is only 3 times communication between server and client in2 image, hence the server negotiates not to perform full handshake.
Session resumption time limit is 7200 seconds.
But setting the cleansession flag to 1 will always perform full handshake which means no session resumption.
I feel it was a good decision taken by PAHO people who made clean session flag linked with session resumption because mosquitto client provided in github lacks this inbuilt feature of session resumption.
Go through the specification of MQTT v3.1.1
Or refer MQTT specification in their website
As a part of my project I am using XBee. I want sample Python code to make two XBees to communicate with each other in Windows. I have written code, but it has a problem.
What would like to sent a message like "hello" from one XBee, and it should be printed on the other XBee side. How can I do this?
Take a look at the great python-xbee library, and Digi's examples.digi.com as two excellent resources for someone new to the XBee. Between those two sites, you should be able to get your XBee radios joined to each other (using the second link) and then get them working in Python (with the first link).
Before doing anything else you have to configure the devices, use XCTU software:
First device - Coordinator API mode:
- ID 7777(or any random value)
- DL set to FFFF
Second device - Router AT mode:
- ID 7777(has to be the same for every device)
- DL set to 0
Code for coordinator (listen mode):
import serial
import time
from xbee import ZigBee
PORT = "COM1" #change the port if you are not using Windows to whatever port you are using
BAUD_RATE = 9600
ser = serial.Serial(PORT, BAUD_RATE)
# Create API object
xbee = ZigBee(ser)
# Continuously read and print packets
while True:
try:
response = xbee.wait_read_frame()
print("\nPacket received at %s : %s" %(time.time(), response))
except KeyboardInterrupt:
ser.close()
break
Code for the remote device:
import serial
PORT = "COM1" #change the port if you are not using Windows to whatever port you are using
BAUD_RATE = 9600
ser = serial.Serial(PORT, BAUD_RATE)
while True:
try:
data = raw_input("Send:")
ser.write(data) #if you are using python 3 replace data with data.encode()
except KeyboardInterrupt:
ser.close()
break
Run the code and send data from the remote device to the coordinator. You will be able to see the packets printed in the console and in the rx_data field will be the payload.
I hope this is helpful.
Hi I am figuring out a way to listen to a socket and connect to a different socket(on same ip but different port number) simultaneously in the same program.when I listen to a socket then it keeps blocking until it receives some message so I am not able to listen and connect simultaneously.
I actually need to simulate exchange of LSP packets between different routers. So I am writing a program to simulate a router so as to run it n(number of routers)times.
Could anyone please share on how to proceed ??
If I understood your problem correctly, one of these might help.
Multi-thread or Multi-process
Basically, when you receive a client you can process a client separately in a separate thread or in a new process. You will be able to receive incoming connections and connect to new clients from other sources while processing the ones who are already connected.
Pseudo Code:
main() {
while(1) {
accept client
/*
After the fork or creation of the new thread, the loop goes back to
accepting clients while connected clients are being processed.
*/
fork or create new thread passing and client socket to it
}
}
processClient() {
do whatever you need to do...
}
Select
Select is another good way of doing non-blocking sockets. Select basically waits for data to come (ie. data, new client requests) to the server and processes them one-by-one. The server will not block on accept as it will wait until it receives something before processing it.
Psuedo Code:
main() {
while(1) {
wait on select
if new client {
accept it
}
for client in clients {
if client has data {
process it
}
}
}
}
ePoll (if you're in Linux)
ePoll is similar to Select only it can handle WAY more clients and it's a lot sexier.
Here's a repo that has each of those. My code isn't perfect here as it was a project that I did while in school.
https://github.com/koralarts/ServerBenchmarking
We are working on a C language application which is simple RTSP/RTP client to record video from Axis a number of Cameras. We launch a pthread for each of the camera which establishes the RTP session and begin to record the packets captured using the recvfrom() call.
A single camera single pthread records fine for well over a day without issues.
But testing with more cameras available,about 25(so 25 pthreads), the recording to file goes fine for like 15 to 20 mins and then the recording just stops. The application still keeps running. Its been over a month and a half we have been trying with varied implementations but nothing seems to help. Please provide suggestions.
We are using CentOS 5 platform
Define "record" Does that mean write data to a file? How do you control access to the file?
You can't have several threads all trying to write at the exact same time. So the comment by Alon seems to be pertinent. Your write access control machanism has problems.
void *IPThread(void *ptr)
{
//Establish RTSP session
//Bind to RTP ports(video)
//Increase Socket buffer size to 625KB
record_fd=open(record_name, O_CREAT|O_RDWR|O_TRUNC, 0777);
while(1)
{
if(poll(RTP/RTCP ports)) //a timeout value of 1
{
if(RTCP event)
RTCPhandler();
if(RTP event)
{
recvfrom(); //the normal socket api recvfrom
WritePacketToFile(record_fd)
{
//Create new record_fd after 100MB
}
}
}
}
}
even if it is alright to stick to the single threaded implementation why is the multithreaded approach behaving such a way(not recording after ~15 mins)..?