windows Socket简单编程实例

 服务端

#include 
#include 
#include 
#include 

#pragma comment(lib, "Ws2_32.lib")


void error_handing(const char* message)
{
	fputs(message, stderr);
	fputc('\n', stderr);
	exit(1);
}
int main(int argc, char* argv[])
{
	WSADATA wsaData;
	if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
	{
		error_handing("WSAStartup() error");
	}
	SOCKET hServSock, hClntSock;
	SOCKADDR_IN servAddr, clntAddr;
	int szClntAddr;
	char message[] = "hello world!";
	if (argc != 2)
	{
		printf("Usage : %s \n", argv[0]);
		exit(1);
	}
	hServSock = socket(AF_INET, SOCK_STREAM, 0);
	if (hServSock == INVALID_SOCKET)
	{
		error_handing("socket() error");
	}
	memset(&servAddr, 0, sizeof(servAddr));
	servAddr.sin_family = AF_INET;
	servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servAddr.sin_port = htons(atoi(argv[1]));

	if (bind(hServSock, (SOCKADDR*)&servAddr, sizeof(servAddr)) == SOCKET_ERROR)
	{
		error_handing("bind() error");
	}
	if (listen(hServSock, 5) == SOCKET_ERROR)
	{
		error_handing("listen() error");
	}
	szClntAddr = sizeof(clntAddr);
	hClntSock = accept(hServSock, (SOCKADDR*)&clntAddr, &szClntAddr);
	if (hClntSock == INVALID_SOCKET)
	{
		error_handing("accept() error");
	}
	closesocket(hClntSock);
	closesocket(hServSock);


	WSACleanup();
	return 0;
}


客户端

#define _WINSOCK_DEPRECATED_NO_WARNINGS


#include 
#include 
#include 
#include 

#pragma comment(lib, "Ws2_32.lib")

void error_handing(const char* message)
{
	fputs(message, stderr);
	fputc('\n', stderr);
	exit(1);
}

int main(int argc, char* argv[])
{
	WSADATA wsaData;
	if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
	{
		error_handing("WSAStartup() error");
	}
	SOCKET hSocket;
	if (argc != 3)
	{
		error_handing("argc error");
	}
	hSocket = socket(AF_INET, SOCK_STREAM, 0);
	SOCKADDR_IN servAddr;
	memset(&servAddr, 0, sizeof(servAddr));
	servAddr.sin_family = AF_INET;
	servAddr.sin_addr.S_un.S_addr = inet_addr(argv[1]);
	servAddr.sin_port = htons(atoi(argv[2]));
	if (connect(hSocket, (SOCKADDR*)&servAddr, sizeof(servAddr)) == SOCKET_ERROR)
	{
		error_handing("connect error");
	}
	char message[30];
	int strlen = recv(hSocket, message, sizeof(message) - 1, 0);
	if (strlen == -1)
	{
		error_handing("recv error");
	}

	printf("recv message: %s\n", message);

	closesocket(hSocket);

	WSACleanup();

	return 0;
}

你可能感兴趣的:(TCP/IP,windows)