Windows network Programming-C language implements simple UDP protocol Chat

Source: Internet
Author: User
Tags htons

It is similar to writing a server-side program code under the TCP protocol, but because it is a non-connected form, there is no need to listen.

This time, I used a little different idea: I set up a server, with two ports and two sockets, the server as a data forwarding station, so that the client to the UDP protocol communication.

Service-Side code:

/** * UDP/IP Server-side SERVER.C */#include <winsock2.h> #include <stdio.h> #include <string.h> #include <    Time.h> #define True 1#define false 0#define buffsize 1024int main (int argc, char**argv) {int Ret;    Wsadata Wsadata;    SOCKET socket_1;    SOCKET socket_2;    Sockaddr_in clientaddr_1;    int clientaddr_1_len = sizeof (clientaddr_1);    Sockaddr_in clientaddr_2;    int clientaddr_2_len = sizeof (clientaddr_2);    unsigned short port_1 = 5150;    unsigned short port_2 = 8888;    Char Senddata[buffsize];    Char Recvdata[buffsize];        if (ret = WSAStartup (Makeword (2,2), &wsadata))! = 0) {printf ("Wsastartup_error:%d\n", Ret);    Exit (1);        } if ((Socket_1 = Socket (Af_inet, sock_dgram, ipproto_udp) = = = Invalid_socket) {printf ("socket_1_error\n");    Exit (1);    }//The port variable is converted from host byte order to bit network byte order clientaddr_1.sin_family = Af_inet; Clientaddr_1.sin_port = htons (port_1); Clientaddr_1.sin_addr. S_un.    S_ADDR = htonl (Inaddr_any);        Bind this address information to the socket using bind if (Bind (socket_1, (SOCKADDR *) &clientaddr_1, clientaddr_1_len) = = Socket_error) {        printf ("Bind_socket_1_error:%d\n", socket_error);    Exit (1);        } if ((Socket_2 = Socket (Af_inet, sock_dgram, ipproto_udp) = = = Invalid_socket) {printf ("socket_2_error\n");    Exit (1);    }//The port variable is converted from host byte order to bit network byte order clientaddr_2.sin_family = Af_inet;    Clientaddr_2.sin_port = htons (port_2); Clientaddr_2.sin_addr. S_un.    S_ADDR = htonl (Inaddr_any);        Bind this address information to the socket using bind if (Bind (socket_2, (SOCKADDR *) &clientaddr_2, clientaddr_2_len) = = Socket_error) {        printf ("Bind_socket_2_error:%d\n", socket_error);    Exit (1);    } printf ("Make connection successful!"); The server acts as a broker//for two IP forwarding messages while (true) {//receives data sent by ip:192.168.1.2 Recvfrom (socket_1, RecvData, buffs       IZE, 0, (sockaddr*) &clientaddr_1, &clientaddr_1_len); strcpy (SendData, RecvData); Forward data to ip:192.168.1.6 if (Ret = SendTo (socket_2, SendData, Buffsize, 0, (sockaddr*) &clientaddr_2, clientaddr_2_        Len)) < 0) printf ("Send failed!\n"); Receive ip:192.168.1.6 sent data recvfrom (socket_2, RecvData, Buffsize, 0, (sockaddr*) &clientaddr_2, &clientaddr_2_l        EN);        strcpy (SendData, RecvData); Forward data to ip:192.168.1.2 if (Ret = SendTo (socket_1, SendData, Buffsize, 0, (sockaddr*) &clientaddr_1, clientaddr_1_    Len)) < 0) printf ("Send failed!\n");    } closesocket (socket_1);    Closesocket (socket_2); After the application finishes docking processing, call WSACleanup if (wsacleanup () = = Socket_error) {printf ("Wsacleanup_error:%d\n", Wsagetlasterr        or ());    Exit (1);    } system ("Pause"); return 0;}

But there will be a small problem, the first data sent to the client's data can not be received, and to run successfully must first send a message, and then open the second client (step seems to be so, the previous period of time to write, forget ... =)

Client 1 Code:

/** * UDP/IP Client client.c */#include <winsock2.h> #include <stdio.h> #include <stdlib.h> #include < String.h> #include <time.h> #define true 1#define false 0#define buffsize 1024int main (int argc, CHAR**ARGV) {in    T Ret;    Wsadata Wsadata;    SOCKET Sendsocket;    Sockaddr_in clientaddr;    int clientaddrlen = sizeof (CLIENTADDR);    unsigned short Port = 5150;    Char Senddata[buffsize];    Char Recvdata[buffsize];    time_t Rawtime;        if (ret = WSAStartup (Makeword (2,2), &wsadata))! = 0) {printf ("Wsastartup_error:%d\n", Ret);    Exit (1);        } if ((Sendsocket = socket (af_inet, SOCK_DGRAM, ipproto_udp) = = = Invalid_socket) {printf ("sendsocket_error\n");    Exit (1);    } clientaddr.sin_family = Af_inet;    Clientaddr.sin_port = htons (port); Clientaddr.sin_addr. S_un. S_ADDR = inet_addr ("192.168.1.2");//native IPV4 address printf ("Connect to ip:%s Port:%d\n", Inet_ntoA (CLIENTADDR.SIN_ADDR), Ntohs (Clientaddr.sin_port));    Puts ("-----start chatting!-----");    Such a loop chat algorithm abruptly the UDP protocol with the previous TCP protocol, the same as the chat program ... The difference between UDP and TCP is not very good to be felt.        But I don't have a good way yet. while (true) {//Send data printf ("\NC.C.:");        scanf ("%s", SendData);        strcat (SendData, "\t____");        Time (&rawtime);        strcat (SendData, CTime (&rawtime)); if (Ret = SendTo (Sendsocket, SendData, Buffsize, 0, (sockaddr*) &clientaddr, Clientaddrlen)) < 0) printf (        "Send failed!\n");  Receive data if (Ret = Recvfrom (Sendsocket, RecvData, Buffsize, 0, (sockaddr*) &clientaddr, &clientaddrlen)) >=        0) printf ("Lulu:%s\n", recvdata);    Else printf ("Receive failed!\n");    } closesocket (Sendsocket);        if (wsacleanup () = = Socket_error) {printf ("Wsacleanup_error:%d\n", WSAGetLastError ());    Exit (1);    } system ("Pause"); return 0;}

According to the idea can write the client 2 code, the code is basically the same, that is, the port number can not be the same, need to correspond to the service side given another port number:

/** * UDP/IP Client client.c */#include <winsock2.h> #include <stdio.h> #include <stdlib.h> #include < String.h> #include <time.h> #define true 1#define false 0#define buffsize 1024int main (int argc, CHAR**ARGV) {in    T Ret;    Wsadata Wsadata;    SOCKET Sendsocket;    Sockaddr_in clientaddr;    int clientaddrlen = sizeof (CLIENTADDR);    unsigned short Port = 8888;    Char Senddata[buffsize];    Char Recvdata[buffsize];    time_t Rawtime;        if (ret = WSAStartup (Makeword (2,2), &wsadata))! = 0) {printf ("Wsastartup_error:%d\n", Ret);    Exit (1);        } if ((Sendsocket = socket (af_inet, SOCK_DGRAM, ipproto_udp) = = = Invalid_socket) {printf ("sendsocket_error\n");    Exit (1);    } clientaddr.sin_family = Af_inet;    Clientaddr.sin_port = htons (port); Clientaddr.sin_addr. S_un. S_ADDR = inet_addr ("192.168.1.2");/** * The IPV4 address of the computer for the server-side program * Obviously this whole chat program requires at least two computers, a computer canServer and client, and another computer for the client. Or three computers are more difficult to confuse, one as a service, and the other two are clients.    */printf ("Connect to ip:%s Port:%d\n", Inet_ntoa (CLIENTADDR.SIN_ADDR), Ntohs (Clientaddr.sin_port));    Puts ("-----start chatting!-----"); while (true) {//Receive data if (Ret = Recvfrom (Sendsocket, RecvData, Buffsize, 0, (sockaddr*) &clientaddr, &A mp        Clientaddrlen)) >= 0) printf ("c.c.:%s\n", RecvData);        Else printf ("Receive failed!\n");        Send data printf ("\ n lulu:");        scanf ("%s", SendData);        strcat (SendData, "\t____");        Time (&rawtime);        strcat (SendData, CTime (&rawtime)); if (Ret = SendTo (Sendsocket, SendData, Buffsize, 0, (sockaddr*) &clientaddr, Clientaddrlen)) < 0) printf (    "Send failed!\n");    } closesocket (Sendsocket);        if (wsacleanup () = = Socket_error) {printf ("Wsacleanup_error:%d\n", WSAGetLastError ());    Exit (1);    } system ("Pause"); return 0;}

Windows network Programming-C language implements a simple UDP 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.