Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1119272
  • 博文数量: 284
  • 博客积分: 8223
  • 博客等级: 中将
  • 技术积分: 3188
  • 用 户 组: 普通用户
  • 注册时间: 2008-12-01 13:26
文章分类

全部博文(284)

文章存档

2012年(18)

2011年(33)

2010年(83)

2009年(147)

2008年(3)

分类: C/C++

2009-10-20 16:48:55

基本上同TCP,
服务器:
 

#include <winsock2.h>
#include <stdio.h>
#include <stdlib.h>
#pragma comment(lib,"ws2_32.lib")//增加几个相关lib库


#define DEFAULT_PORT 5150
#define DEFAULT_BUFFER 4096


int main(int argc,char **argv)
{
    WSADATA wsd;
    SOCKET sListen;
    int iAddrSize, ret;
    struct sockaddr_in local;
    char szBuff[DEFAULT_BUFFER];

    if(WSAStartup(MAKEWORD(2,2), &wsd)!=0)
    {
        printf("Failed to load Winsock!\n");
        return 1;
    }
    sListen = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
    if(sListen == SOCKET_ERROR)
    {
        printf("%d\n", WSAGetLastError());
    }

    local.sin_addr.s_addr = htonl(INADDR_ANY);
    local.sin_family = AF_INET;
    local.sin_port = htons(5000);


    if(bind(sListen, (struct sockaddr *)&local, sizeof(local))==SOCKET_ERROR)
    {
        printf("%d\n", WSAGetLastError());
        return 1;
    }

    while(1)
    {
        iAddrSize = sizeof(local);
        ret = recvfrom(sListen, szBuff, DEFAULT_BUFFER, 0, (struct sockaddr *)&local, &iAddrSize);

        if(ret==0) break;
        else if(ret == SOCKET_ERROR)
        {
            printf("%d\n", WSAGetLastError());
            break;
        }else{
            szBuff[ret]='\0';
            printf("RECV:%s", szBuff);
        }
        
    }
    closesocket(sListen);
    WSACleanup();
    return 0;

}


客户端:

#include <winsock2.h>
#include <stdio.h>
#include <stdlib.h>
#pragma comment(lib,"ws2_32.lib")//增加几个相关lib库


#define DEFAULT_PORT 5150
#define DEFAULT_BUFFER 4096


int main(int argc,char **argv)
{
    WSADATA wsd;
    SOCKET sListen;
    int iAddrSize;
    struct sockaddr_in local;

    if(WSAStartup(MAKEWORD(2,2), &wsd)!=0)
    {
        printf("Failed to load Winsock!\n");
        return 1;
    }
    sListen = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
    if(sListen == SOCKET_ERROR)
    {
        printf("%d\n", WSAGetLastError());
    }

    local.sin_port = htons(5000);
    local.sin_family=AF_INET;
    local.sin_addr.s_addr = inet_addr("10.144.15.6");

    iAddrSize = sizeof(local);
    
    char msg[100]=" i am toy\n";
    sendto(sListen, msg, strlen(msg),0, (struct sockaddr *)&local, iAddrSize);

    closesocket(sListen);
    WSACleanup();
    return 0;

}


阅读(677) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~