欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

前段时间做了个TCP/IP通讯的项目,现记录一下一些关键的内容

程序员文章站 2022-03-04 22:16:28
...

先构建一个服务端:

#include "stdafx.h"
#include <WinSock2.h>
#include <iostream>
#include <fstream>
#include <direct.h>
#pragma comment(lib,"ws2_32.lib")   //静态加入一个lib文件
int main()
{
	//开始时创建文件夹
	string pathname[5] = { "D:/*****",
						"D:/******",
						"D:/******" ,
						"D:/******",
						"D:/******" };
	for (int i = 0; i < 5; i++)
	{
		if (0 !=pathname[i].c_str())
		{
			// if this folder not exist, create a new one.
			_mkdir(pathname[i].c_str());   // 返回 0 表示创建成功,-1 表示失败
		}
	}
	

	WORD sockVersion = MAKEWORD(2, 2);
	WSADATA wsaData;
	if (WSAStartup(sockVersion, &wsaData) != 0)
		return 0;
	SOCKET listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (listenSocket == INVALID_SOCKET)
	{
		printf("套接字创建失败");
		WSACleanup();
		return 0;
	}
	/*绑定IP和端口*/
	//配置监听地址和端口
	sockaddr_in addrListen;
	addrListen.sin_family = AF_INET;     //指定IP格式
	addrListen.sin_port = htons(4001);   //绑定端口号
	//addrListen.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");  
	addrListen.sin_addr.S_un.S_addr = INADDR_ANY;    //表示任何IP 
	if (bind(listenSocket, (SOCKADDR*)&addrListen, sizeof(addrListen)) == SOCKET_ERROR)  //(SOCKADDR*)
	{
		printf("绑定失败");
		closesocket(listenSocket);
		return 0;
	}
	/*开始监听*/
	if (listen(listenSocket, 5) == SOCKET_ERROR)
	{
		printf("监听出错");
		closesocket(listenSocket);
		return 0;
	}
	/*等待连接,连接后建立一个新的套接字*/
	SOCKET revSocket;  //对应此时所建立连接的套接字的句柄
	sockaddr_in remoteAddr;   //接收连接到服务器上的地址信息
	int remoteAddrLen = sizeof(remoteAddr);
	printf("等待连接...\n");
	/*等待客户端请求,服务器接收请求*/
	revSocket = accept(listenSocket, (SOCKADDR*)&remoteAddr, &remoteAddrLen);  //等待客户端接入,直到有客户端连接上来为止
	if (revSocket == INVALID_SOCKET)
	{
		printf("客户端发出请求,服务器接收请求失败:\n", WSAGetLastError());
		closesocket(listenSocket);
		WSACleanup();
		return 0;
	}
	else
	{
		printf("客服端与服务器建立连接成功:%s \n", inet_ntoa(remoteAddr.sin_addr));
	}
	char revData[2048];
	memset(revData, 0, 2048);
	while (true)
	{
		
		/*通过建立的连接进行通信*/
		int res = recv(revSocket, revData, 2048, 0);
		if (res <= 0)
		{
			if(res==0)
				printf("Connection closed\n");
			else
				printf("recv failed: %d\n", WSAGetLastError());
			printf("等待连接...\n");
			revSocket = accept(listenSocket, (SOCKADDR*)&remoteAddr, &remoteAddrLen);  //等待客户端接入,直到有客户端连接上来为止
			if (revSocket == INVALID_SOCKET)
			{
				printf("客户端发出请求,服务器接收请求失败:\n", WSAGetLastError());
				closesocket(listenSocket);
				WSACleanup();
				return 0;
			}
			else
			{
				printf("客服端与服务器建立连接成功:%s \n", inet_ntoa(remoteAddr.sin_addr));
			}
		}

		int len = 0;
		while ((BYTE)(revData[len]) != 0 && len<2048)
		{
			len++;              //读取revData的实际长度
		}
		fstream ftxt;           //写入txt
		ftxt.open("./data.txt", ios::out | ios::app | ios::binary);
		if (ftxt.fail())
		{
			cout << "can not open it" << endl;
			getchar();
			return 0;
		}
		ftxt.write(revData, len);
		ftxt.close();
		memset(revData, 0, 2048);
	}

在客服端中:

#include<winsock.h>
HICON m_hIcon;
SOCKET socket_client;
WORD ver = MAKEWORD(2, 0);
WSADATA wsadata;
if (WSAStartup(ver, &wsadata))
{
	MessageBox(_T("load winsock dll failing"), _T("load"));
	return FALSE;
}
//create socket
//socket_client = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
socket_client = socket(AF_INET, SOCK_STREAM, 0);
if (INVALID_SOCKET == socket_client)
{
	MessageBox(_T("create socket failing"), _T("create"));
	return FALSE;
}
//connet server
sockaddr_in addr;
memset(&addr, 0, sizeof(sockaddr_in));
addr.sin_family = AF_INET;
//addr.sin_port = htons(10000);
addr.sin_port = htons(4001);
//addr.sin_addr.S_un.S_addr = inet_addr("192.168.1.127");
char IP[20];
memset(IP, 0, 20);
GetPrivateProfileString("SET", "IP", "", IP, 20, "./IP.ini");
//addr.sin_addr.S_un.S_addr = inet_addr("192.168.1.49");
addr.sin_addr.S_un.S_addr = inet_addr(IP);
if (connect(socket_client, (sockaddr*)&addr, sizeof(sockaddr)))
{
	MessageBox(_T("connect server failed"), _T("connect"));
	return FALSE;
}

//在适当的位置向下发送数据
char send_flag[] = { 0xc0,0x03,0xc0 };
send(socket_client, send_flag, 3, NULL);
相关标签: TCP/IP