client.cpp
#include
#include
#pragma comment(lib, "ws2_32")
#define LEN 1024
#define TRUE 1
#define FALSE_F -1
#define OK 1
#define ERROR_R -1
int main()
{
int i=100;
int ret;
char buf1[LEN];
char buf[LEN];
WORD wdVersionRequired;
WSADATA wsaData;
memset(buf, 0, sizeof(buf));
memset(buf1, 0, sizeof(buf1));
wdVersionRequired = MAKEWORD(2, 2); /* 2.2°汾 */
WSAStartup(wdVersionRequired, &wsaData);
while(i--)
{
SOCKET sock;
sockaddr_in saServer;
sock = socket(AF_INET, SOCK_STREAM, 0);
if (SOCKET_ERROR == sock)
{
return FALSE;
}
memset(&saServer, 0, sizeof(saServer));
saServer.sin_family = AF_INET;
saServer.sin_addr.S_un.S_addr = inet_addr("192.168.2.80");
saServer.sin_port = htons(8066);
if(connect(sock, (const sockaddr*)&saServer, sizeof(sockaddr)) != 0)
{
printf("connect error/n");
}
memset(buf, 0, sizeof(buf));
strcpy(buf, "hello world");
if(0 == send(sock, buf, strlen(buf), 0))
{
printf("send error/n");
break;
}
ret = recv(sock, buf1, sizeof(buf1), 0);
buf1[ret]='/0';
printf("buf1: %s/n/n", buf1);
closesocket(sock);
}
WSACleanup();
return 1;
}
================================================
/*******************************
server.cpp
********************************/
#include
#include
#pragma comment(lib, "ws2_32")
#define LEN 1024
#define OK 1
#define ERROR_R -1
#define FALSE 0
#define TRUE 1
DWORD WINAPI AnswerThread(LPVOID lparam)
{
int err;
char buf[32]="";
char recvbuf[32]="yes receive!!";
SOCKET ClientSocket=(SOCKET)(LPVOID)lparam;
// memset(recvbuf, 0, sizeof(recvbuf));
memset(buf, 0, sizeof(buf));
err = recv(ClientSocket, buf, sizeof(buf), 0);
send(ClientSocket, recvbuf, strlen(recvbuf), 0);
buf[err]='/0';
printf("revc: %s/n", buf);
closesocket(ClientSocket);
return OK;
}
int main()
{
int err;
SOCKET sock;
SOCKET sClient;
DWORD dwThreadId;
WORD wdVersionRequired;
HANDLE hThread;
WSADATA wsaData;
sockaddr_in saServer, cli_addr;
int len = sizeof(cli_addr);
wdVersionRequired = MAKEWORD(2, 2); //³ÌÐòҪʹÓÃ2.2°æ±¾
//×¢Ò⺯Êý·µ»ØÖµ£¬0±íʾÕý³£
if ((err = WSAStartup(wdVersionRequired, &wsaData)) != 0)// ³õʼ»¯WinSock¿â¡£
return FALSE;
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
printf(" create socket error/n");
}
saServer.sin_family = AF_INET;
saServer.sin_addr.S_un.S_addr = inet_addr("192.168.2.80");
saServer.sin_port = htons(8066);
if ((err = bind(sock, (const sockaddr *)&saServer, sizeof(sockaddr)))!= 0)
{
printf("failed bind/n");
}
if ((err = listen(sock, 100)) != 0)//listen()¼àÌý
{
printf("failed listen/n");
}
while(1)
{
sClient = accept(sock, (struct sockaddr*)&cli_addr, &len);
Sleep(1000);
hThread=CreateThread(NULL,NULL, AnswerThread,(LPVOID)sClient, 0, &dwThreadId);
if(hThread==NULL)
printf("CreatThread AnswerThread() failed./n");
else
printf("CreateThread OK./n");
}
closesocket(sock);
WSACleanup();
return TRUE;
}