1. 程式人生 > >UDP windows下socket程式設計例項

UDP windows下socket程式設計例項

Server 端程式原始碼:
#include <stdio.h>
#include <Winsock2.h>

void main()
{
SOCKET socket1;

//InitWinsock();
 WSADATA wsaData;
    int iErrorCode;
    if (WSAStartup(MAKEWORD(2,1),&wsaData)) //呼叫Windows Sockets DLL
    { 
         printf("Winsock無法初始化!\n");
         WSACleanup();
         return;
    }

    printf("伺服器開始建立SOCKET。\n");
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]="\0";
printf("waiting for message from others-------------\n");
if (recvfrom(socket1,buffer,sizeof(buffer),0,(struct sockaddr*)&from,&fromlen)!=SOCKET_ERROR)
{
printf("Received datagram from %s--%s\n",inet_ntoa(from.sin_addr),buffer);
////給cilent發信息
sendto(socket1,buffer,sizeof(buffer),0,(struct sockaddr*)&from,fromlen);

}
//Sleep(1000);
}
closesocket(socket1);
}



Client端原始碼:



#include <stdio.h>
#include <Winsock2.h>

void main()
{
SOCKET socket1;
//InitWinsock();
 WSADATA wsaData;
    int iErrorCode;
    if (WSAStartup(MAKEWORD(2,1),&wsaData)) //呼叫Windows Sockets DLL
    { 
         printf("Winsock無法初始化!\n");
         WSACleanup();
         return;
    }

printf("伺服器開始建立SOCKET。\n");
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("221.223.16.32"); ///server的地址

socket1=socket(AF_INET,SOCK_DGRAM,0);
while (1)
{
    char buffer[1024]="\0";
    printf("input message\n");
    scanf("%s",buffer);
//    printf("%s",buffer);
    if (strcmp(buffer,"bye")==0)
    {
        printf("退出!\n");
        Sleep(100);
        closesocket(socket1);
        break;
    }

    if (sendto(socket1,buffer,sizeof(buffer),0,(struct sockaddr*)&server,len)!=SOCKET_ERROR)
    {
        //printf("sending..\n");
        Sleep(100);
        if (recvfrom(socket1,buffer,sizeof(buffer),0,(struct sockaddr*)&server,&len) != SOCKET_ERROR)
        printf("rece from server:%s\n",buffer);
    }
    }
    closesocket(socket1);
}


至於功能,看看原始碼就知道了,以上的原始碼編譯除錯工作正常!