TCP Sockets (Server/client implementation)

Source: Internet
Author: User
Tags ack bind printf socket strlen port number htons
SocketsConcept: The combination of source IP address and destination IP address and source port number and destination port number is called socket. The servers and services that are used to identify client requests. Classification:
Stream sockets (SOCK_STREAM) datagram Sockets (SOCK_DGRAM) raw sockets (Sock_raw) TCP Sockets (Stream sockets)TCP Socket Workflow:
First, the server-side starts the process, calling the socket to create a stream socket descriptor based on the TCP protocol. Second, the service process invokes the bind named socket, binding the socket descriptor to the local address and the local port. Again, the server-side calls listen and starts listening for the client's socket connection request. Next, the client creates the socket descriptor and calls connect to submit the connection request to the server side. After the server receives the client connection request, it calls accept, accepts and creates a new socket descriptor to establish a connection with the client, and then the original socket descriptor continues to listen for the client's connection request. The client and server-side new sockets transmit data, call write or send to the other, call read or recv to receive data. Code
Server.c #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #include <stdlib.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string.h> #
include<pthread.h> static void usage (const char* proc) {printf ("Usage:%s [local_ip] [local_port]\n", proc);
    } int start_up (const char* _ip,int _port) {int SK = socket (af_inet,sock_stream,0);
        if (SK < 0) {perror ("socket");
    Exit (2);
    } struct sockaddr_in local;
    local.sin_family = af_inet;
    Local.sin_port = htons (_port);

    LOCAL.SIN_ADDR.S_ADDR = inet_addr (_IP);
        if (bind (SK, struct sockaddr *) &local,sizeof (local) < 0) {perror ("bind");
    Exit (3);
        } if (Listen (sk,10) < 0) {perror ("listen");
    Exit (4);
} return SK;
    } void* handlerquest (void*arg) {//close (LISTEN_SK);
    int new_sk = (int) arg;
    while (1) {char buf[1024];    ssize_t s = Read (New_sk,buf,sizeof (BUF)-1);
            if (S > 0) {buf[s] = 0;
            printf ("client:%s\n", buf);
        Write (New_sk,buf,strlen (BUF));
            } else {close (NEW_SK);
            printf ("Client quit ... \ n");
        Break
        }}} int main (int argc,char* argv[]) {if (argc! = 3) {usage (argv[0]);
    return 1;
    } int listen_sk = START_UP (Argv[1],atoi (argv[2]));
        while (1) {struct SOCKADDR_IN client;

        socklen_t len = sizeof (client);
        int New_sk = Accept (Listen_sk, (struct sockaddr*) (&client), &len);
            if (New_sk < 0) {perror ("accept");
        Continue
} printf ("Get A new client%s:%d\n", Inet_ntoa (CLIENT.SIN_ADDR), Ntohs (Client.sin_port));
        Multi-threaded pthread_t ID;
        Pthread_create (&id,null,handlerquest, (void*) New_sk);
Pthread_detach (ID); Multi-process//pid_t ID = Fork ();
    if (ID < 0)//{//close (NEW_SK);
    }//else if (id = = 0)//{//close (LISTEN_SK);
    if (fork () <0)//{//exit (0);
    }//while (1)//{//char buf[1024];
    ssize_t s = Read (New_sk,buf,sizeof (BUF)-1);
    if (S > 0)//{//Buf[s] = 0;
    printf ("client:%s\n", buf);
    Write (New_sk,buf,strlen (BUF));
    }//else//{//close (NEW_SK);
    printf ("Client quit ... \ n");
    Break
    }//}//Close (NEW_SK);
    }//else//{//close (NEW_SK);
    }//Normal edition//while (1)//{//char buf[1024];
    ssize_t s = Read (New_sk,buf,sizeof (BUF)-1);          if (S > 0)//{//Buf[s] = 0;
    printf ("client:%s\n", buf);
    Write (New_sk,buf,strlen (BUF));
    }//else//{//close (NEW_SK);
    printf ("Client quit ... \ n");
    Break
}//}} return 0; }
client.c #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <string.h> #include <stdlib.h> #include <netinet/in.h> #include <arpa/inet.h> void usage (const char* proc) {pri
NTF ("usage:%s [local_ip] [local_port]\n");
        } int main (int argc,char* argv[]) {if (argc! = 3) {usage (argv[0]);
    return 1;
    } int SK = socket (af_inet,sock_stream,0);
        if (SK <0) {perror ("socket");
    return 1;
    } struct SOCKADDR_IN server;
    server.sin_family = af_inet;
    Server.sin_port = htons (Atoi (argv[2])); 

    SERVER.SIN_ADDR.S_ADDR = inet_addr (argv[1]);
        if (Connect (SK, (struct sockaddr*) &server,sizeof (server)) <0) {perror ("connect");
    Exit (1);
    } Char buf[1024];
        while (1) {printf ("enter#:");

        Fflush (stdout);
        ssize_t s = Read (0,buf,sizeof (BUF)-1);
   if (S > 0) {buf[s-1] = 0;         Write (Sk,buf,strlen (BUF));
            s = Read (Sk,buf,sizeof (BUF)-1);
                if (S > 0) {buf[s] = 0;
            printf ("Server echo#%s\n", buf);
}}} return 0; }
Makefile
. Phony:all
all:tcp_server tcp_client

tcp_client:tcp_client.c
    gcc-o $@ $^ 
tcp_server:tcp_server.c
    gcc-o $@ $^-lpthread
. Phony:clean clean
:
    rm-f tcp_client Tcp_serve
The server exits, the client does not exit, and when the server is run again (the same as the previous port number), the Bind failure occurs.
Reason:
The active closed party will enter the TIME_WAIT state to stay 2MSL (max segment lifetime) time after the last ACK is sent. This TCP/IP is essential, that is, "solution" is not. That's what TCP/IP designers were designed to do. There are two main reasons
Prevent packets from the last connection, re-appear after getting lost, affect new connections (after 2MSL, all duplicates in last connection will disappear) reliable shutdown of TCP connections
The last ACK (FIN) sent at the active shutdown is likely to be lost, when the passive side will resend fin, and if the active side is in the closed state, it will respond to RST rather than ACK. So the active side should be in the TIME_WAIT state, but not closed.
Time_wait does not occupy a significant amount of resources unless it is under attack. Also, if a party send or recv timeout, it will go directly into the closed state
[http://blog.csdn.net/acs713/article/details/28427181]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.