Socket 通信发送和接收数据

//发送数据
void SendData()
{

WORD wVersionRequested;
WSADATA wsaData;
int nErr;

wVersionRequested  = MAKEWORD(1, 1);

nErr = WSAStartup(wVersionRequested, &wsaData);
if (nErr != 0)
{
    return;
}

if (LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1)
{
    WSACleanup();
    return;
}

//创建夽接字
SOCKET socketClient = socket(AF_INET, SOCK_STREAM, 0);

SOCKADDR_IN addrSrv;
addrSrv.sin_family = AF_INET;
addrSrv.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
addrSrv.sin_port = htons(6000);

//向服务器发出连接请求
connect(socketClient, (SOCKADDR*)&addrSrv, sizeof(SOCKADDR));

static int i = 0;
char* chSendBuf =  new char[100];
memset(chSendBuf, '0', 100);
sprintf(chSendBuf, "Send Message %d", i);
i++;


send(socketClient, chSendBuf, 100, 0);
CString edtText(chSendBuf);
m_edtClientShowMessage.SetWindowTextW(edtText);

closesocket(socketClient);
WSACleanup();
delete [] chSendBuf;

}

//接收数据
void ReciveData()
{

//加载接字库
WORD wVersionRequested;
WSADATA wsaData;
int nErr;

wVersionRequested = MAKEWORD(1, 1);

nErr = WSAStartup(wVersionRequested, &wsaData);
if (nErr != 0)
{
    return;
}

if (LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1)
{
    WSACleanup();
    return;
}

//创建用于监听的夽接字
SOCKET socketSrv = socket(AF_INET, SOCK_STREAM, 0);

SOCKADDR_IN addrSrv ;
addrSrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
addrSrv.sin_family = AF_INET;
addrSrv.sin_port = htons(PORT);

//绑定夽接字
bind(socketSrv, (SOCKADDR*)&addrSrv, sizeof(SOCKADDR));
//将夽接字设为监听模式
listen(socketSrv, 5);

SOCKADDR_IN addrClient;
int len = sizeof(SOCKADDR);

while (1)
{
    //等待客户请求到来
    SOCKET sockConn = accept( socketSrv, (SOCKADDR*)&addrClient, &len);
    char recvBuf[BUF_SIZE];
    memset(recvBuf, '0', BUF_SIZE);
    recv(sockConn, recvBuf, BUF_SIZE, 0);
    CString strTemp = _T("Recive Data:");
    CString strRecive(recvBuf);
    strTemp += strRecive;
    m_edtSrvShowMessage.SetWindowText(strTemp);
    //关闭夽接字
    closesocket(sockConn);
    Sleep(2000);
}

}

你可能感兴趣的:(Socket 通信发送和接收数据)