VC環境下UDP Socket程式設計示例
#include <stdio.h>
#include <Winsock2.h>
void main()
{
SOCKET socket1;
WSADATA wsaData;
if
(WSAStartup(MAKEWORD(2,1),&wsaData)) //呼叫Windows Sockets
DLL
{
printf("Winsock無法初始化!n");
WSACleanup();
return;
}
struct sockaddr_in
local;
struct sockaddr_in from;
int fromlen
=sizeof(from);
local.sin_family=AF_INET;
local.sin_port=htons(27015);
///監聽埠
local.sin_addr.s_addr=INADDR_ANY; ///本機
socket1=socket(AF_INET,SOCK_DGRAM,0);
bind(socket1,(struct
sockaddr*)&local,sizeof(local));
while (1)
{
char buffer[1024]="";
printf("waiting-------------n");
if (recvfrom(socket1,buffer,sizeof(buffer),0,(struct
sockaddr*)&from,&fromlen)!=SOCKET_ERROR)
{
printf("Received datagram from
%s--%sn",inet_ntoa(from.sin_addr),buffer);
sendto(socket1,buffer,sizeof(buffer),0,(struct
sockaddr*)&from,fromlen);
}
}
closesocket(socket1);
}
客戶端程式碼:
#include <stdio.h>
#include <Winsock2.h>
void main()
{
SOCKET socket1;
WSADATA wsaData;
if
(WSAStartup(MAKEWORD(2,1),&wsaData)) //呼叫Windows Sockets
DLL
{
printf("Winsock無法初始化!n");
WSACleanup();
return;
}
struct sockaddr_in
server;
int len =sizeof(server);
server.sin_family=AF_INET;
server.sin_port=htons(27015);
///server的監聽埠
server.sin_addr.s_addr=inet_addr("127.0.0.1");
///server的地址
printf("connect the
server...n");
socket1=socket(AF_INET,SOCK_DGRAM,0);
while (1)
{
char buffer[1024]="";
printf("input messagen");
scanf("%s",buffer);
if (strcmp(buffer,"bye")==0)
{
printf("exitn");
Sleep(100);
closesocket(socket1);
break;
}
if(sendto(socket1,buffer,sizeof(buffer),0,(struct
sockaddr*)&server,len)!=SOCKET_ERROR)
{
Sleep(100);
if (recvfrom(socket1,buffer,sizeof(buffer),0,(struct
sockaddr*)&server,&len) != SOCKET_ERROR)
printf("echo from server:%sn",buffer);
}
}
}