poilkjewq
Posts: 16
Joined: Fri Jun 15, 2018 9:50 am

How to continuously send and receive data using TCP server

Tue Jun 19, 2018 1:02 pm

Hello everyone! I am a beginner of raspberry pi.

I am trying to implement TCP server on raspberry pi. I just execute the following code to run TCP server but how to continuously send and receive data using TCP server.

In my project, my connection of the device and raspberry pi like this:
[Serial Device]===[usb to serial db9 adaptor]===[raspberry pi]===[Ethernet]===[Computer(Putty)]

I want to send command to the serial device and then get the response from the serial device by using TCP server.

Code: Select all

#include<stdio.h>
#include<sys/socket.h>
#include<arpa/inet.h> //inet_addr
 
int main()
{
    int socket_desc , new_socket , c;
    struct sockaddr_in server , client;
     
    //Create socket
    socket_desc = socket(AF_INET , SOCK_STREAM , 0);
    if (socket_desc == -1)
    {
        printf("Could not create socket");
    }
     
    //Prepare the sockaddr_in structure
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_port = htons( 8888 );
     
    //Bind
    if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0)
    {
        puts("bind failed");
    }
    puts("bind done");
     
    //Listen
    listen(socket_desc , 3);
     
    //Accept and incoming connection
    puts("Waiting for incoming connections...");
    c = sizeof(struct sockaddr_in);
    new_socket = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c);
    if (new_socket<0)
    {
        perror("accept failed");
    }
     
    puts("Connection accepted");
 
    return 0;
}
Thank You for your helping!!!!! :D :D :D

User avatar
topguy
Posts: 4937
Joined: Tue Oct 09, 2012 11:46 am
Location: Trondheim, Norway

Re: How to continuously send and receive data using TCP server

Tue Jun 19, 2018 1:18 pm

Probably most practical to use two threads.
- One that listens to serial and send received data on socket.
- The other listens to socket and sends sends the received data to serial.

Could maybe also be used in one thread but then you should learn to use the "select" function: http://man7.org/linux/man-pages/man2/select.2.html

poilkjewq
Posts: 16
Joined: Fri Jun 15, 2018 9:50 am

Re: How to continuously send and receive data using TCP server

Tue Jun 19, 2018 1:55 pm

topguy wrote:
Tue Jun 19, 2018 1:18 pm
Probably most practical to use two threads.
- One that listens to serial and send received data on socket.
- The other listens to socket and sends sends the received data to serial.

Could maybe also be used in one thread but then you should learn to use the "select" function: http://man7.org/linux/man-pages/man2/select.2.html
Thank you for your reply!!! :D
Could you please tell me more detail by using two thread? or give me some information to read it?
Thanks a lot.

Return to “Networking and servers”