windows环境下使用socket进行tcp通信

 客户端

#define WIN32 _LEAN_AND_MEAN
#define _WINSOCK_DEPRECATED_NO_WARNINGS 
#include<iostream>
#include<WinSock2.h>
#include<Windows.h>
#include<stdio.h>

using namespace std;
#pragma comment (lib, "ws2_32.lib") 
//#ws2_32.lib
int main()
{
	WORD ver = MAKEWORD(2, 2);
	WSADATA dat;
	WSAStartup(ver, &dat);
	//1.创立socket 1.IPV4网络  类型:数据流  TCP
	//套接字
	SOCKET _sock = socket(AF_INET, SOCK_STREAM, 0);
	//2.connect连接服务器
	sockaddr_in _sin = {};
	_sin.sin_family = AF_INET;
	_sin.sin_port = htons(4567);//host_to_net unsigned short
	_sin.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
	if (SOCKET_ERROR == connect(_sock, (sockaddr*)&_sin, sizeof(_sin)))
	{
		printf("链接失败\n");
	}
	else {
		printf("链接网络成功\n");
	};
	//3,recv接收数据 监听网络接口
	char recvbuffer[1024] = {};
	;
	if (SOCKET_ERROR == recv(_sock, recvbuffer, sizeof(recvbuffer), 0))
	{
		printf("接受失败\n");
	}
	else {
		printf("接受成功\n");
	}
	cout << recvbuffer << endl;

	//6.关闭
	closesocket(_sock);
	WSACleanup();
	return 0;
}

服务端

#define WIN32 _LEAN_AND_MEAN
#define _WINSOCK_DEPRECATED_NO_WARNINGS 
#include<iostream>
#include<WinSock2.h>
#include<Windows.h>

using namespace std;
#pragma comment (lib, "ws2_32.lib") 
//#ws2_32.lib
int main()
{
	WORD ver = MAKEWORD(2, 2);
	WSADATA dat;
	WSAStartup(ver, &dat);
	//1.创立socket 1.IPV4网络  类型:数据流  TCP
	//套接字
	SOCKET _sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	//2.bind绑定接收客户端
	sockaddr_in _sin = {};
	_sin.sin_family = AF_INET;
	_sin.sin_port = htons(4567);//host_to_net unsigned short
	_sin.sin_addr.S_un.S_addr = INADDR_ANY;//inet_addr("127.0.0.1")
	if (SOCKET_ERROR==bind(_sock, (sockaddr*)&_sin, sizeof(_sin)) )
	{
		printf("绑定失败\n");
	}
	else {
		printf("绑定网络成功\n");
	};
	//3,listen 监听网络接口
	if (SOCKET_ERROR == listen(_sock, 5))
	{
		printf("监听失败\n");
	}
	else {
		printf("监听成功\n");
	}

	//4.接受数据
	sockaddr_in _clientaddr = {};
	int naddrlen = sizeof(_clientaddr);
	SOCKET _clientsocket = INVALID_SOCKET;
	while (true)
	{
		_clientsocket = accept(_sock, (sockaddr*)&_clientaddr, &naddrlen);
		if (_clientsocket == INVALID_SOCKET)
		{
			printf("错误,接受无效客户端socket....\n");
		}
		cout << "新客户端加入: ip= " << inet_ntoa(_clientaddr.sin_addr)<<endl; 
		//5.send 向客户端发送一条数据
		char msgBuf[] = "hello, I'M server";
		send(_clientsocket, msgBuf, strlen(msgBuf) + 1, 0);
	}
	//6.关闭
	closesocket(_sock);
	WSACleanup();
	return 0;
}

 

上一篇:高效开发Maven架构设计图解/掌握项目工程自动化技巧(精通篇二)


下一篇:DB_GPT excel研究-源码分析