服务端代码:
#include"iostream"
#include
#pragma comment(lib,"ws2_32")
#include
using namespace std;
int main()
{
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
SOCKET s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
sockaddr_in sockaddr;
sockaddr.sin_family = PF_INET;
sockaddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
sockaddr.sin_port = htons(827);
bind(s, (SOCKADDR*)&sockaddr, sizeof(SOCKADDR));
listen(s, 1);
SOCKADDR clientAddr;
int nSize = sizeof(SOCKADDR);
SOCKET clientSock;
clientSock = accept(s, (SOCKADDR*)&clientAddr, &nSize);
send(clientSock,
"helllo client \r\n",
strlen("hello client \r\n") + sizeof(char),
NULL);
closesocket(clientSock);
closesocket(s);
WSACleanup();
return 0;
}
客户端代码:
#include"iostream"
#include
#include
#pragma comment(lib,"ws2_32")
using namespace std;
int main()
{
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
SOCKET s = socket(PF_INET,SOCK_STREAM, IPPROTO_TCP);
sockaddr_in sockAddr;
sockAddr.sin_family = PF_INET;
sockAddr.sin_addr.S_un.S_addr = inet_addr("127,0,0,1");
sockAddr.sin_port = htons(827);
connect(s, (SOCKADDR*)&sockAddr, sizeof(SOCKADDR));
char szBuffer[MAXBYTE] = { 0 };
recv(s, szBuffer, MAXBYTE, NULL);
printf("szBuffer=%s\r\n", szBuffer);
closesocket(s);
WSACleanup();
return 0;
}