编程语言
首页 > 编程语言> > 基于TCP的socket编程(C++)

基于TCP的socket编程(C++)

作者:互联网

服务器端

//TCP服务端
#include<winsock2.h>                                //包含头文件
#include<stdio.h>
#include<windows.h>
#include<iostream>
#include<ws2tcpip.h>

#pragma comment(lib, "WS2_32.lib")                 //显示连接套接字库

using namespace std;

int main()
{
	WSADATA data;                                 //定义WSADATA结构体对象
	WORD w = MAKEWORD(2, 0);                      //定义版本号码
	::WSAStartup(w, &data);                       //初始化套接字
	SOCKET s;                                     //定义连接套接字和数据收发套接字句柄
	s = ::socket(AF_INET, SOCK_STREAM, 0);        //创建tcp套接字
	sockaddr_in addr;                             //定义套接字地址结构
	addr.sin_family = AF_INET;                    //初始化地址结构
	addr.sin_port = htons(75);
	addr.sin_addr.S_un.S_addr = INADDR_ANY;
	::bind(s, (sockaddr*)&addr, sizeof(addr));    //绑定套接字
	::listen(s, 5);                               //监听套接字,5并不是时间而是最大监听5个
	cout << "服务端已启动..." << endl;

	sockaddr_in addr2;
	int n = sizeof(addr2);
	SOCKET s1;
	char sztext[] = "您已成功连接服务端...\n";
	char buffer[17];
	while (true)
	{

		s1 = ::accept(s, (sockaddr*)&addr2, &n);            //接受连接请求
		if (s1 != NULL)                                     //不能使用s1 != nullptr
		{
			cout <<"地址:" << inet_ntop(AF_INET, (const void*)&addr2.sin_addr, buffer, 17) << "已经连接到服务端" << endl;
			::send(s1, sztext, sizeof(sztext), 0);             //向客户端发送信息
		}
		::closesocket(s);                                  //关闭套接字句柄
		::closesocket(s1);
		::WSACleanup();                                    //释放套接字库

		if (getchar())
		{
			return 0;
		}
		else
		{
			::Sleep(100);
		}
	}
}

  客户端:

/*
* TCP客户端代码
*/

#include<winsock2.h>
#include<stdio.h>
#include<Windows.h>
#include<iostream>
#include<ws2tcpip.h>

#pragma comment(lib, "WS2_32.lib")                  //显示连接套接字库

using namespace std;

int main()
{
	WSADATA data;                                  //定义WSADATA结构体对象
	WORD w = MAKEWORD(2, 0);                       //定义版本号码
	::WSAStartup(w, &data);                        //初始化套接字库
	SOCKET s = ::socket(AF_INET, SOCK_STREAM, 0);  //定义连接套接字句柄
	sockaddr_in addr;                             //定义套接字地址结构
	addr.sin_family = AF_INET;
	addr.sin_port = htons(75);
	inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr.S_un.S_addr);
	cout << "客户端已启动..." << endl;
	::connect(s, (sockaddr*)&addr, sizeof(addr));
	char sztext[50];
	::recv(s,sztext, sizeof(sztext), 0);
	cout<<sztext<<endl;
	::closesocket(s);
	::WSACleanup();
	if (getchar())
	{
		return 0;
	}
	else
	{
		::Sleep(100);              
	}
	return 0;
}

  

标签:addr,AF,C++,TCP,接字,include,sin,INET,socket
来源: https://www.cnblogs.com/xcxfury001blogs/p/16472499.html