socket通信(服务器端)
#include<stdio.h>
#include<winsock2.h>
#include<string.h>
#pragma comment(lib,"ws2_32.lib")
#include<windows.h>
DWORD WINAPI clientThread(LPVOID lpParameter)
{
int sockfd = (int)lpParameter;
char caMsg[1024] = {'\0'};
while(1)
{
memset(caMsg,0,sizeof(caMsg));
scanf("%s",caMsg);
int ret = send(sockfd,caMsg,strlen(caMsg),0);
if(SOCKET_ERROR == ret)
{
printf("send errror\n");
}
}
return 0;
}
int main(void)
{
WORD sockVersion = MAKEWORD(2,2);
WSADATA wsaData;
if(WSAStartup (sockVersion ,&wsaData )!= 0)
{
return 0;
}
SOCKET Server = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(Server == INVALID_SOCKET )
{
printf("create socket failed!");
system("pause");
return 0;
}
struct sockaddr_in serverAddr;
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(888);
serverAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
if(bind(Server,(LPSOCKADDR)&serverAddr,sizeof(serverAddr))==SOCKET_ERROR)
{
perror("bind failed!");
exit(EXIT_FAILURE);
}
if(listen(Server,10)==SOCKET_ERROR)
{
printf("listen error!");
return 0;
}
struct sockaddr_in clientAddr;
int clientSockfd = -1;
int iLen = sizeof(clientAddr);
while(1)
{
printf("Accept connect ... \n");
clientSockfd = accept(Server,(struct sockaddr*)&clientAddr,&iLen);
if(-1 == clientSockfd)
{
perror("accept");
break;
}
printf("client ip:%s,port:%u \n",inet_ntoa(clientAddr.sin_addr) ,clientAddr.sin_port);
CreateThread(NULL,0,clientThread,(LPVOID)clientSockfd,0,NULL);
char recvData[128];
while(1)
{
int ret = recv(clientSockfd,recvData,128,0);
if(ret > 0)
{
printf(" recv data:%s\n",recvData);
}
}
}
closesocket(Server);
return 0;
}
客户端:
#include<stdio.h>
#include<winsock2.h>
#include<string.h>
#pragma warning(disable:4068)
#pragma comment(lib,"ws2_32.lib")
#include<windows.h>
DWORD WINAPI serverThread(LPVOID lpParameter)
{
int sockfd = (int)lpParameter;
char caMsg[128] = {'\0'};
while(1)
{
int ret = recv(sockfd,caMsg,128,0);
if(ret > 0)
{
printf("recv data: %s\n",caMsg);
}
memset(caMsg,0,sizeof(caMsg));
}
}
int main(void)
{
WORD sockVersion = MAKEWORD(2,2);
WSADATA data;
if(WSAStartup (sockVersion,&data)!=0)
{
return 0;
}
SOCKET sclient = socket (AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(sclient==INVALID_SOCKET)
{
printf("invalid socket !");
return 0;
}
struct sockaddr_in servAddr;
servAddr.sin_family = AF_INET;
servAddr.sin_port = htons(888);
servAddr.sin_addr.S_un.S_addr = inet_addr ("127.0.0.1");
if(connect(sclient,(struct sockaddr*)&servAddr,sizeof(servAddr))== SOCKET_ERROR)
{
printf("connect error!");
closesocket(sclient);
return 0;
}
printf("Connect success \n");
CreateThread(NULL,0,serverThread,(LPVOID)sclient,NULL,0);
char caMsg[128];
while(1)
{
memset(caMsg,0,sizeof(caMsg));
scanf("%s",caMsg);
int ret = send(sclient,caMsg,128,0);
}
closesocket(sclient);
WSACleanup();
return 0;
}