socket编程入门篇(一)

  • Post author:
  • Post category:其他


先贴代码:

服务端代码:

#include <Winsock2.h>
#include <iostream>
int main(int argc, char* argv[]) 
{
	WSADATA wsaData;
	WORD sockVersion = MAKEWORD(2, 2);
	if (WSAStartup(sockVersion, &wsaData) != 0) {
		return 0;
	}
	SOCKET sListen = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (sListen == INVALID_SOCKET) {
		printf("socket error\n");
		return 0;
	}
	struct sockaddr_in sin;
	sin.sin_family = AF_INET;
	sin.sin_port = htons(4500);
	sin.sin_addr.S_un.S_addr = INADDR_ANY;
	if (bind(sListen, (LPSOCKADDR)&sin, sizeof(sin)) == SOCKET_ERROR) {
		printf("socket error\n");
		closesocket(sListen);
		return 0;
	}
	if (listen(sListen, 5) == SOCKET_ERROR) {
		printf("socket error\n");
		closesocket(sListen);
		return 0;
	}
	struct sockaddr_in remoteAddr;
	SOCKET sClient;
	int nAddrLen = sizeof(remoteAddr);
	char revData[255];
	while (TRUE) {
		sClient = accept(sListen, (SOCKADDR*)&remoteAddr, &nAddrLen);
		if (sClient == SOCKET_ERROR) {
			printf("accept() error\n");
			continue;
		}
		printf("接受到一个连接:%s \r\n", inet_ntoa(remoteAddr.sin_addr));
		int ret = recv(sClient, revData, 255, 0);
		if (ret > 0) {
			revData[ret] = 0x00;
			printf(revData);
		}
		char* buff = (char*)"\r\nHello, my friend\r\n";
		send(sClient, buff, strlen(buff), 0);
		closesocket(sClient);
	}
	closesocket(sListen);
	WSACleanup();
	return 0;
}

服务端调用socket(),bind(),listen(),accept()函数。调用send和recv函数传递信息。

客户端代码:

#include "WinSock2.h"
#include <iostream>
using namespace std;
int main(int argc, char* argv[]) 
{
	WSADATA wsaData;
	WORD sockVersion = MAKEWORD(2, 2);
	if (WSAStartup(sockVersion, &wsaData) != 0) {
		return 0;
	}
	SOCKET sClient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (sClient == SOCKET_ERROR) {
		printf("socket error\n");
		return 0;
	}
	struct sockaddr_in servAddr;
	servAddr.sin_family = AF_INET;
	servAddr.sin_port = htons(4500);
	servAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
	if (connect(sClient, (SOCKADDR*)&servAddr, sizeof(servAddr)) == SOCKET_ERROR) {
		printf("socket error\n");
		closesocket(sClient);
		return 0;
	}
	char* buff = (char*)"\r\nHello, my friend\r\n";
	send(sClient, buff, strlen(buff), 0);
	char revData[255];
	int ret = recv(sClient, revData, 255, 0);
	if (ret > 0) {
		revData[ret] = 0x00;
		printf(revData);
	}
	closesocket(sClient);
	WSACleanup();
	return 0;
}

客户端调用socket(),connect()函数。 调用send和recv函数传递信息。

项目需要配置ws2_32.lib,并关闭SDL检查。

参考博客:

https://www.cnblogs.com/jikexianfeng/p/5729168.html



版权声明:本文为qq_39790992原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。