Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1109667
  • 博文数量: 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:38:20

废话少说,看代码:
服务器端:
 

#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, sClient;
    int iAddrSize, ret;
    struct sockaddr_in local, client;
    char szBuff[DEFAULT_BUFFER];

    if(WSAStartup(MAKEWORD(2,2), &wsd)!=0)
    {
        printf("Failed to load Winsock!\n");
        return 1;
    }
    sListen = socket(AF_INET, SOCK_STREAM, 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;
    }
    listen(sListen, 8);

    while(1)
    {
        iAddrSize = sizeof(local);
        sClient = accept(sListen, (struct sockaddr *)&local, &iAddrSize);
        if(sClient == INVALID_SOCKET)
        {
            printf("%d\n", WSAGetLastError());
            break;
        }else{
            ret = recv(sClient, szBuff, DEFAULT_BUFFER, 0);
            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_STREAM, 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);
    connect(sListen, (struct sockaddr *)&local, iAddrSize);
    
    char msg[100]=" i am toy\n";
    send(sListen, msg, strlen(msg),0);

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

}


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