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

Day.55————C++ socket编程实现简单的UDP、TCP通信(服务端+客户端)

程序员文章站 2022-06-06 16:06:13
...

UDP通信

UDPClient.cpp

#include<WINSOCK2.H>
#include<iostream>
#pragma comment(lib,"WS2_32.lib")
using namespace std;

int main()
{
	WSADATA wsaData;//初始化
	SOCKET SendSocket;
	sockaddr_in RecvAddr;//服务器地址
	int Port = 4000;//服务器监听地址
	char SendBuf[1024];//发送数据的缓冲区
	int BufLen = 1024;//缓冲区大小
	//初始化Socket
	WSAStartup(MAKEWORD(2, 2), &wsaData);
	//创建Socket对象
	SendSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	//设置服务器地址
	RecvAddr.sin_family = AF_INET;
	RecvAddr.sin_port = htons(Port);
	RecvAddr.sin_addr.s_addr = inet_addr("10.132.19.223");
	//向服务器发送数据报
	printf("Sending a datagram to the receiver...\n");
	cin >> SendBuf;
	sendto(SendSocket, SendBuf, BufLen, 0, (SOCKADDR *)&RecvAddr, sizeof(RecvAddr));
	//发送完成,关闭Socket
	printf("finished sending,close socket.\n");
	closesocket(SendSocket);
	printf("Exting.\n");
	WSACleanup();
	return 0;
}

UDPServer.cpp

#include<WINSOCK2.H>
#include<iostream>
#pragma comment(lib,"WS2_32.lib")
using namespace std;
int main()
{
	WSADATA wsaData;//初始化
	SOCKET RecvSocket;
	sockaddr_in RecvAddr;//服务器地址
	int Port = 4000;//服务器监听地址
	char RecvBuf[1024];//发送数据的缓冲区
	int BufLen = 1024;//缓冲区大小
	sockaddr_in SenderAddr;
	int SenderAddrSize = sizeof(SenderAddr);
	//初始化Socket
	WSAStartup(MAKEWORD(2, 2), &wsaData);


	//创建接收数据报的socket
	RecvSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	//将socket与制定端口和0.0.0.0绑定
	RecvAddr.sin_family = AF_INET;
	RecvAddr.sin_port = htons(Port);
	RecvAddr.sin_addr.s_addr = htonl(INADDR_ANY);
	bind(RecvSocket, (SOCKADDR *)&RecvAddr, sizeof(RecvAddr));
	//调用Recvfrom函数在绑定的socket上接收数据
	printf("receiving datagrams...\n");
	recvfrom(RecvSocket, RecvBuf, BufLen, 0, (SOCKADDR *)&SenderAddr, &SenderAddrSize);


	//关闭socket,结束接收数据
	printf("finished receiving,closing socket..\n");
	cout << endl;
	cout << RecvBuf;
	closesocket(RecvSocket);
	//释放资源,退出
	printf("Exiting.\n");
	WSACleanup();
	return 0;
}

TCP通信

TCPClient.cpp

#include<iostream>
#include <winsock2.h>
using namespace std;
#pragma comment(lib, "ws2_32.lib")

int main()
{
    //加载套接字库
    WSADATA wsaData;
    int iRet =0;
    iRet = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (iRet != 0)
    {
        cout << "WSAStartup(MAKEWORD(2, 2), &wsaData) execute failed!" << endl;
        return -1;
    }
    if (2 != LOBYTE(wsaData.wVersion) || 2 != HIBYTE(wsaData.wVersion))
    {
        WSACleanup();
        cout << "WSADATA version is not correct!" << endl;
        return -1;
    }
 
    //创建套接字
    SOCKET clientSocket = socket(AF_INET, SOCK_STREAM, 0);
    if (clientSocket == INVALID_SOCKET)
    {
        cout << "clientSocket = socket(AF_INET, SOCK_STREAM, 0) execute failed!" << endl;
        return -1;
    }
 
    //初始化服务器端地址族变量
    SOCKADDR_IN srvAddr;
    srvAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
    srvAddr.sin_family = AF_INET;
    srvAddr.sin_port = htons(6000);
 
    //连接服务器
    iRet = connect(clientSocket, (SOCKADDR*)&srvAddr, sizeof(SOCKADDR));
    if (0 != iRet)
    {
        cout << "connect(clientSocket, (SOCKADDR*)&srvAddr, sizeof(SOCKADDR)) execute failed!" << endl;
        return -1;
    }
 
    //接收消息
    char recvBuf[100];
    recv(clientSocket, recvBuf, 100, 0);
    printf("%s\n", recvBuf);
 
    //发送消息
    char sendBuf[100];
    sprintf_s(sendBuf, "Hello, This is client %s", "兔子");
    send(clientSocket, sendBuf, strlen(sendBuf)+1, 0);
 
    //清理
    closesocket(clientSocket);
    WSACleanup();
    system("pause");
    return 0;
}

TCPServer.cpp

#include<iostream>
#include<WinSock2.h>
#pragma comment(lib, "ws2_32.lib")
#define CONNECT_NUM_MAX 10
using namespace std;
 
int main()
{
    //加载套接字库
    WSADATA wsaData;
    int iRet = 0;
    iRet = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (iRet != 0)
    {
        cout << "WSAStartup(MAKEWORD(2, 2), &wsaData) execute failed!" << endl;;
        return -1;
    }
    if (2 != LOBYTE(wsaData.wVersion) || 2 != HIBYTE(wsaData.wVersion))
    {
        WSACleanup();
        cout << "WSADATA version is not correct!" << endl;
        return -1;
    }
 
    //创建套接字
    SOCKET serverSocket = socket(AF_INET, SOCK_STREAM, 0);
    if (serverSocket == INVALID_SOCKET)
    {
        cout << "serverSocket = socket(AF_INET, SOCK_STREAM, 0) execute failed!" << endl;
        return -1;
    }
 
    //初始化服务器地址族变量
    SOCKADDR_IN addrSrv;
    addrSrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
    addrSrv.sin_family = AF_INET;
    addrSrv.sin_port = htons(6000);
 
    //绑定
    iRet = bind(serverSocket, (SOCKADDR*)&addrSrv, sizeof(SOCKADDR));
    if (iRet == SOCKET_ERROR)
    {
        cout << "bind(serverSocket, (SOCKADDR*)&addrSrv, sizeof(SOCKADDR)) execute failed!" << endl;
        return -1;
    }
 
 
    //监听
    iRet = listen(serverSocket, CONNECT_NUM_MAX);
    if (iRet == SOCKET_ERROR)
    {
        cout << "listen(serverSocket, 10) execute failed!" << endl;
        return -1;
    }
 
    //等待连接_接收_发送
    SOCKADDR_IN clientAddr;
    int len = sizeof(SOCKADDR);
    while (1)
    {
        SOCKET connSocket = accept(serverSocket, (SOCKADDR*)&clientAddr, &len);
        if (connSocket == INVALID_SOCKET)
        {
            cout << "accept(serverSocket, (SOCKADDR*)&clientAddr, &len) execute failed!" << endl;
            return -1;
        }
 
        char sendBuf[100];
        sprintf_s(sendBuf, "Welcome %s", inet_ntoa(clientAddr.sin_addr));
        send(connSocket, sendBuf, strlen(sendBuf)+1, 0);
 
        char recvBuf[100];
        recv(connSocket, recvBuf, 100, 0);
        printf("%s\n", recvBuf);
        closesocket(connSocket);
    }
     
    system("pause");
    return 0;
}