Windows network Programming-C language implements simple TCP protocol Chat

Source: Internet
Author: User
Tags htons

The TCP protocol is similar to when the caller is on the phone and is talking to each other at the moment. Ensure that both parties are online in order to transfer data. UDP protocol is like a mailbox, does not guarantee that the other party must be waiting for your mail and the other side you can also send data to each other. In fact, the TCP protocol, UDP protocol, there are important TCP protocol three handshake (establish connection) and four waves (close connection) and so on the Internet also explained very detailed, so I don't say more.

Server-Side program code:

/* * Server-side SERVER.C * */#include <winsock2.h> #include <stdio.h> #define true 1#define false 0#define Af_inef                2//I use VC + + written, do not know why the header file does not have this definition, so you can only define a # define Buffsize 1024int main (int argc, CHAR**ARGV) {int    Ret;    Wsadata Wsadata;    SOCKET Listeningsocket;    SOCKET newconnection;    Sockaddr_in serveraddr;    Sockaddr_in clientaddr;    int clientaddrlen = sizeof (CLIENTADDR);    unsigned short Port = 5150;    Char Senddata[buffsize];    Char Recvdata[buffsize];        if (ret = WSAStartup (Makeword (2,2), &wsadata))! = 0) {printf ("Wsastartup_error:%d\n", Ret);    return false;        }//Create a socket to listen for client connections if (Listeningsocket = socket (AF_INEF, Sock_stream, ipproto_tcp)) = = Invalid_socket) {        printf ("Socket_error:%d\n", invalid_socket);    return false; }/* Creates a SOCKADDR_IN structure that tells Bind that we want to listen for connections on all interfaces on Port 5150 * *   The port variable is converted from host byte order to bit network byte order serveraddr.sin_family = AF_INEF;    Serveraddr.sin_port = htons (port); Serveraddr.sin_addr. S_un.    S_ADDR = htonl (Inaddr_any);         Bind this address information to the socket using bind if (Bind (Listeningsocket, (SOCKADDR *) &serveraddr, sizeof (serveraddr)) = = Socket_error) {        printf ("Bind_error:%d\n", socket_error);    return false; }//Listening for client connections.        Here are 5 backlog if (Listen (Listeningsocket, 5) = = Socket_error) {printf ("Listen_error:%d\n", socket_error);    return false;         } if ((Newconnection = Accept (Listeningsocket, (SOCKADDR *) &clientaddr, &clientaddrlen)) = = = Invalid_socket) {        printf ("Accpet_error:%d\n", invalid_socket);        Closesocket (Listeningsocket);    return false;    } printf ("A connection was detected:%s Port:%d\n", Inet_ntoa (CLIENTADDR.SIN_ADDR), Ntohs (Clientaddr.sin_port));        When the connection arrives, accept a new connection while (true) {//Receive data Ret = recv (newconnection, RecvData, buffsize, 0); if (Ret > 0) printf ("C.C.:%s\n", recvdata);        else if (Ret < 0) printf ("Recv_error:%d\n", socket_error);            else {printf ("Exit program, Chat end!");        Break        } printf ("\ n lulu:");        scanf ("%s", &senddata);            if (Send (Newconnection, SendData, buffsize, 0) = = socket_error) {printf ("message sent failed!\n");        Break    }}//After completing the newly accepted connection, close these sockets closesocket (Newconnection) with the Closesocket API;    Closesocket (Listeningsocket); After the application finishes docking processing, call WSACleanup if (wsacleanup () = = Socket_error) {printf ("Wsacleanup_error:%d\n", Wsagetlasterr        or ());    return false; } return 0;}

Client-side program code:

/* * Client CLIENT.C * */#include <winsock2.h> #include <stdio.h> #define true 1#define false 0#define Af_inef 2#def Ine buffsize 1024int Main (int argc, char**argv) {intret; Wsadatawsadata; SOCKETs; sockaddr_inserveraddr;unsigned Shortport = 5150;charsenddata[buffsize];charrecvdata[buffsize];if (Ret = WSAStartup ( Makeword (2,2), &wsadata))! = 0) {printf ("Wsastartup_error:%d\n", Ret); return false;} if ((s = socket (af_inet, Sock_stream, ipproto_tcp)) = = Invalid_socket) {printf ("Socket_error:%d\n", invalid_socket); return false;} serveraddr.sin_family = af_inet; Serveraddr.sin_port = htons (port); Serveraddr.sin_addr. S_un.  S_ADDR = inet_addr ("192.168.1.102"); Test if (Connect (s, (sockaddr*) &serveraddr, sizeof (serveraddr)) = = Socket_error) {printf ("connect_") with the native IPV4 address. ERROR:%d\n ", socket_error); Closesocket (s); return false;} while (true) {printf ("\nc.c.:"); scanf ("%s", &senddata), if (send (S, SendData, buffsize, 0) = = socket_error) {printf (" Message sent failed!\n "); Ret = recv (S, RecvData, Buffsize,0); if (Ret > 0) printf ("Lulu:%s\n", recvdata), else if (Ret < 0) printf ("Recv_error:%d\n", socket_error); else{printf (" The other side quit the program, chat end! "); Break;}} Closesocket (s); if (wsacleanup () = = Socket_error) {printf ("Wsacleanup_error:%d\n", WSAGetLastError ()); return false;} return 0;}

Operation Result:

Emmm ... For all possible errors I have added a function name prefix that will make mistakes so that I can find the error.

Other books explained in detail, do not reveal their level of 233 ... The last little thank you for your study ~

Windows network Programming-C language implements simple TCP protocol Chat

Related Article

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.