Recently learning Windows network programming, just do Udpsocket program, paste up:
Server Framework functions:
Socket (); Bind (); Recfrom (); SendTo (); Closesocket ();
Client Framework functions:
Socket (); Recfrom (); SendTo (); Closesocket ();
Second, the specific code is shown below, you are welcome to Exchange
First, the server is opened for listening, so the server code is as follows:
Udpse.cpp:Defines the entry point for the console application.
//
#include "stdafx.h"
#include <winsock2.h>
#pragma comment (lib, "Ws2_32.lib")
#include < IOSTREAM>
int main (int argc, char* argv[])
{
wsadata wsadata;
//Initialize Socket
wsastartup (Makeword (2,2), &wsadata);
//Create SOCKET
socket recvsocket;
Recvsocket=socket (AF_INET,SOCK_DGRAM,IPPROTO_UDP);
//to bind the socket
sockaddr_in readdr;
reAddr.sin_family=AF_INET;
readdr.sin_port=htons (5678);
readdr.sin_addr. S_un. S_addr=htonl (Inaddr_any);
bind (Recvsocket, (SOCKADDR *) &readdr,sizeof (READDR));
//calls the Recvfrom function binding on the socket receiving client data
//get the current system time Sdatatime,
systemtime St;
getlocaltime (&ST);
//char sdatatime[30];
printf ("Current system server time:%4d-%2d-%2d%2d:%2d:%2d\n", St.wyear,st.wmonth,st.wday,st.whour,st.wminute, St.wsecond);
Char recvbuf[1024];
int buflen=1024;
Two temporarily useless, client properties
Sockaddr_in fromclientaddr;
int fromclientsize=sizeof (FROMCLIENTADDR);
int Lbuf=recvfrom (recvsocket,recvbuf,buflen,0, (SOCKADDR *) &fromclientaddr,&fromclientsize);
recvbuf[lbuf]= ' + ';
printf ("Client IP address is:%s, port is:%d\n, the data content is:%s\n", Inet_ntoa (fromclientaddr.sin_addr), fromclientaddr.sin_port,recvbuf );
printf ("Receive complete, close socket\n");
Closesocket (Recvsocket);
Release Resources and exit
WSACleanup ();
return 0;
}
Three, the client sends the data, the code is as follows:
Udp.cpp:Defines the entry point for the console application.
//
#include "stdafx.h"
#include <winsock2.h>
#pragma comment (lib, "Ws2_32.lib")
int main (int argc, char* argv[])
{
Wsadata Wsadata;
Initialize socket
WSAStartup (Makeword (2,2), &wsadata);
Socket initialization
SOCKET Sendsocket;
Sendsocket=socket (AF_INET,SOCK_DGRAM,IPPROTO_UDP);
Set the incoming server address
Sockaddr_in seaddr;
Seaddr.sin_family=af_inet;
Seaddr.sin_port=htons (5678);
Seaddr.sin_addr. S_un. S_ADDR=INET_ADDR ("127.0.0.1");//;htonl (Inaddr_any)
Initialization
Char sendbuf[1024]= "Hello Wang Shu Qing";
int buflen=1024;
Sending data to the server
printf ("Please input send data to server: \ n");
scanf ("%s", sendbuf);
Buflen=strlen (SENDBUF);
Binding
SendTo (sendsocket,sendbuf,buflen,0, (SOCKADDR *) &seaddr,sizeof (SEADDR));
Send complete, close socket
printf ("Send complete, close socket\n");
Closesocket (Sendsocket);
Release Resources and exit
WSACleanup ();
return 0;
}
Four:
VC Environment Window Network program: UDP Socket Program