VC環境下window網路程式:UDP Socket程式

wsqyouth發表於2015-05-03

最近在學Windows網路程式設計,正好在做UDPsocket的程式,貼上來:

伺服器框架函式:

             socket();    bind();    recfrom();  sendto();  closesocket();

客戶機框架函式:

           socket();      recfrom();  sendto();  closesocket();

二、具體程式碼如下所示,歡迎大家一起交流

首先要開啟伺服器進行監聽,所以伺服器server程式碼如下:

// 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;
 //初始化socket
 WSAStartup(MAKEWORD(2,2),&wsaData);
    //建立socket
 SOCKET recvSocket;
    recvSocket=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
 //將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));
 //呼叫recvfrom函式繫結在socket接收到客戶機資料
 //獲取當前系統時間 sDataTime,
 SYSTEMTIME st;
 GetLocalTime(&st);
 //char sDataTime[30];
 printf("當前系統伺服器時間:%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;
 //兩個暫時沒用的,客戶機屬性
 sockaddr_in FromclientAddr;
 int FromclientSize=sizeof(FromclientAddr);
 int lbuf=recvfrom(recvSocket,recvBuf,bufLen,0,(SOCKADDR *)&FromclientAddr,&FromclientSize);
 recvBuf[lbuf]='\0';

 printf("客戶機IP地址是:%s,埠是:%d\n,發來的資料內容是:%s\n",inet_ntoa(FromclientAddr.sin_addr),FromclientAddr.sin_port,recvBuf);

 printf("接收完成,關閉socket\n");
 closesocket(recvSocket);
 //釋放資源並退出
 WSACleanup();
 return 0;
}

 

三,客戶機傳送資料,程式碼如下:

// 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;
 //初始化socket
 WSAStartup(MAKEWORD(2,2),&wsaData);
 //套接字初始化
 SOCKET sendSocket;
 sendSocket=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
 //設定即將連伺服器地址
 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)
 
 //初始化
 char sendBuf[1024]="hello wang shu qing";
 int bufLen=1024;
    //向伺服器傳送資料
 printf("請輸入傳送資料給伺服器:\n");
 scanf("%s",sendBuf);
    bufLen=strlen(sendBuf);
 //繫結
 sendto(sendSocket,sendBuf,bufLen,0,(SOCKADDR *)&seAddr,sizeof(seAddr));
 //傳送完成,關閉socket
 printf("傳送完成,關閉socket\n");
 closesocket(sendSocket);
 //釋放資源並退出
 WSACleanup();
 return 0;
}

 四,效果圖:

 

  

相關文章