一、流程图
二、注意事项
1.连接ws2_32库
2.使用inet_addr函数报错解决
三、代码
服务端:
#include "stdio.h"
#include "stdlib.h"
#include "winsock2.h"
int main(int argc, char* argv[])
{
WSADATA wsaData;
SOCKET hSerSocket,hClntSock;
SOCKADDR_IN servAddr, clntAddr;
char message[] = "hello world!";
int szClntAddr;
int size;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
printf("WSAStartup() error!\n");
hSerSocket = socket(PF_INET, SOCK_STREAM, 0);
if (hSerSocket == INVALID_SOCKET)
printf("socket() error!\n");
memset(&servAddr, 0, sizeof(servAddr));
servAddr.sin_family = AF_INET;
servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
servAddr.sin_port = htons(9190);
if (bind(hSerSocket, (SOCKADDR*)&servAddr, sizeof(servAddr)) == SOCKET_ERROR)
printf("bind() error!\n");
if(listen(hSerSocket, 5) == SOCKET_ERROR)
printf("listen() error!\n");
szClntAddr = sizeof(clntAddr);
hClntSock = accept(hSerSocket, (SOCKADDR*)&clntAddr,&szClntAddr);
if(hClntSock == INVALID_SOCKET)
printf("accept() error!\n");
send(hClntSock,message,sizeof(message),0);
closesocket(hSerSocket);
closesocket(hClntSock);
WSACleanup();
return 0;
}
客户端:
#include "stdio.h"
#include "stdlib.h"
#include "winsock2.h"
int main(int argc, char* argv[])
{
WSADATA wsaData;
SOCKET hSocket;
SOCKADDR_IN servAddr;
char message[30];
int strLen;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
printf("WSAStartup() error!\n");
hSocket = socket(PF_INET, SOCK_STREAM, 0);
if (hSocket == INVALID_SOCKET)
printf("socket() error!\n");
memset(&servAddr, 0, sizeof(servAddr));
servAddr.sin_family = AF_INET;
servAddr.sin_addr.s_addr = inet_addr(argv[1]);
servAddr.sin_port = htons(atoi(argv[2]));
if (connect(hSocket, (SOCKADDR*)&servAddr, sizeof(servAddr)) == SOCKET_ERROR)
printf("connect() error!\n");
strLen = recv(hSocket, message, sizeof(message) - 1, 0);
if (strLen == -1)
printf("recv() error!\n");
printf("Message:%s\n",message);
closesocket(hSocket);
WSACleanup();
return 0;
}