您当前的位置:首页 > 计算机 > 编程开发 > VC/VC++

c++ Socket实现TCP

时间:09-16来源:作者:点击数:

c++ Socket实现TCP

参考1

客户端
//客户端
#include<iostream>
#include<winsock.h>
#pragma comment(lib,"ws2_32.lib")
using namespace std;
void initialization();
int main() {
    //定义长度变量
    int send_len = 0;
    int recv_len = 0;
    //定义发送缓冲区和接受缓冲区
    char send_buf[100];
    char recv_buf[100];
    //定义服务端套接字,接受请求套接字
    SOCKET s_server;
    //服务端地址客户端地址
    SOCKADDR_IN server_addr;
    initialization();
    //填充服务端信息
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
    server_addr.sin_port = htons(1234);
    //创建套接字
    s_server = socket(AF_INET, SOCK_STREAM, 0);
    if (connect(s_server, (SOCKADDR*)& server_addr, sizeof(SOCKADDR)) == SOCKET_ERROR) {
        cout << "服务器连接失败!" << endl;
        WSACleanup();
    }
    else {
        cout << "服务器连接成功!" << endl;
    }

    //发送,接收数据
    while (1) {
        cout << "请输入发送信息:";
        cin >> send_buf;
        send_len = send(s_server, send_buf, 100, 0);
        if (send_len < 0) {
            cout << "发送失败!" << endl;
            break;
        }
        recv_len = recv(s_server, recv_buf, 100, 0);
        if (recv_len < 0) {
            cout << "接受失败!" << endl;
            break;
        }
        else {
            cout << "服务端信息:" << recv_buf << endl;
        }

    }
    //关闭套接字
    closesocket(s_server);
    //释放DLL资源
    WSACleanup();
    return 0;
}
void initialization() {
    //初始化套接字库
    WORD w_req = MAKEWORD(2, 2);//版本号
    WSADATA wsadata;
    int err;
    err = WSAStartup(w_req, &wsadata);
    if (err != 0) {
        cout << "初始化套接字库失败!" << endl;
    }
    else {
        cout << "初始化套接字库成功!" << endl;
    }
    //检测版本号
    if (LOBYTE(wsadata.wVersion) != 2 || HIBYTE(wsadata.wHighVersion) != 2)
 {
        cout << "套接字库版本号不符!" << endl;
        WSACleanup();
    }
    else {
        cout << "套接字库版本正确!" << endl;
    }
    //填充服务端地址信息

}

服务端

//服务器
#include<iostream>
#include<winsock.h>
#pragma comment(lib,"ws2_32.lib")
using namespace std;
void initialization();
int main() {
    //定义长度变量
    int send_len = 0;
    int recv_len = 0;
    int len = 0;
    //定义发送缓冲区和接受缓冲区
    char send_buf[100];
    char recv_buf[100];
    //定义服务端套接字,接受请求套接字
    SOCKET s_server;
    SOCKET s_accept;
    //服务端地址客户端地址
    SOCKADDR_IN server_addr;
    SOCKADDR_IN accept_addr;
    initialization();
    //填充服务端信息
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
    server_addr.sin_port = htons(1234);
    //创建套接字
    s_server = socket(AF_INET, SOCK_STREAM, 0);
    if (bind(s_server, (SOCKADDR*)& server_addr, sizeof(SOCKADDR)) == SOCKET_ERROR) {
        cout << "套接字绑定失败!" << endl;
        WSACleanup();
    }
    else {
        cout << "套接字绑定成功!" << endl;
    }
    //设置套接字为监听状态
    if (listen(s_server, SOMAXCONN) < 0) {
        cout << "设置监听状态失败!" << endl;
        WSACleanup();
    }
    else {
        cout << "设置监听状态成功!" << endl;
    }
    cout << "服务端正在监听连接,请稍候...." << endl;
    //接受连接请求
    len = sizeof(SOCKADDR);
    s_accept = accept(s_server, (SOCKADDR*)& accept_addr, &len);
    if (s_accept == SOCKET_ERROR) {
        cout << "连接失败!" << endl;
        WSACleanup();
        return 0;
    }
    cout << "连接建立,准备接受数据" << endl;
    //接收数据
    while (1) {
        recv_len = recv(s_accept, recv_buf, 100, 0);
        if (recv_len < 0) {
            cout << "接受失败!" << endl;
            break;
        }
        else {
            cout << "客户端信息:" << recv_buf << endl;
        }
        cout << "请输入回复信息:";
        cin >> send_buf;
        send_len = send(s_accept, send_buf, 100, 0);
        if (send_len < 0) {
            cout << "发送失败!" << endl;
            break;
        }
    }
    //关闭套接字
    closesocket(s_server);
    closesocket(s_accept);
    //释放DLL资源
    WSACleanup();
    return 0;
}
void initialization() {
    //初始化套接字库
    WORD w_req = MAKEWORD(2, 2);//版本号
    WSADATA wsadata;
    int err;
    err = WSAStartup(w_req, &wsadata);
    if (err != 0) {
        cout << "初始化套接字库失败!" << endl;
    }
    else {
        cout << "初始化套接字库成功!" << endl;
    }
    //检测版本号
    if (LOBYTE(wsadata.wVersion) != 2 || HIBYTE(wsadata.wHighVersion) != 2) {
        cout << "套接字库版本号不符!" << endl;
        WSACleanup();
    }
    else {
        cout << "套接字库版本正确!" << endl;
    }
    //填充服务端地址信息

}

参考2

Client:


#include <iostream>
#include <winsock2.h>
#include <ws2tcpip.h>  
#pragma comment(lib, "ws2_32.lib")  
#define PORT 8080

int main() 
{
	// 初始化 Winsock
	WSADATA wsaData;
	if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
	{
		return 0;
	}

	// 创建 socket
	SOCKET socket = ::socket(AF_INET, SOCK_STREAM, 0);
	if (socket == INVALID_SOCKET)
	{
		return 0;
	}
	// 设置服务器信息
	SOCKADDR_IN serverAddress;
	serverAddress.sin_family = AF_INET;
	serverAddress.sin_port = htons(8080); // 服务器的端口号
	//serverAddress.sin_addr.s_addr = inet_addr(ipBuffer); // 服务器的 IP 地址
	inet_pton(AF_INET, "127.0.0.1", &serverAddress.sin_addr.s_addr);

	// 连接到服务器
	if (connect(socket, (SOCKADDR*)&serverAddress, sizeof(serverAddress)) == SOCKET_ERROR)
	{
		closesocket(socket);
		WSACleanup();
		return 0;
	}
	
	std::string data = "机器切割状态为:";
	if (send(socket, data.c_str(), data.size(), 0) == SOCKET_ERROR)
	{
		closesocket(socket);
		WSACleanup();
		return 0;
	}

	Sleep(100);


	// 关闭 socket
	closesocket(socket);

	// 清理 Winsock
	WSACleanup();

	return 0;
}

Server:

#include <iostream>
#include <winsock2.h>
#include <ws2tcpip.h>  
#pragma comment(lib, "ws2_32.lib")  
#define PORT 8080

int main()
{
    // 初始化Winsock  
    WSADATA wsa;
    if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) {
        std::cerr << "WSAStartup failed.\n";
        return 1;
    }
    //创建socket文件描述符
    SOCKET server_fd = ::socket(AF_INET, SOCK_STREAM, 0);
    if (server_fd == INVALID_SOCKET)
    {
        perror("socket failed");
        exit(EXIT_FAILURE);
    }
    //定义sockaddr_in 结构体变量 ,并清零
    sockaddr_in  address;
    memset(&address, 0, sizeof(address));
    int addrlen = sizeof(address);
    address.sin_family = AF_INET;
    address.sin_port = htons(PORT);
    address.sin_addr.s_addr = INADDR_ANY;

    //绑定socket与端口
    if (bind(server_fd, (LPSOCKADDR)&address, sizeof(address)) == SOCKET_ERROR)
    {
        perror("bind failed");
        exit(EXIT_FAILURE);
    }

    //监听端口
    if (listen(server_fd, 3) < 0)
    {
        perror("Fiald to listen socket");
        exit(EXIT_FAILURE);
    }

    std::cout << "server is listening" << std::endl;

    int  new_socket;
    // 等待客户端连接  
    struct sockaddr_in client_addr;
    socklen_t client_addr_len = sizeof(client_addr);

    if ((new_socket = accept(server_fd, (SOCKADDR*)&client_addr, &client_addr_len)) == -1)
    {
        std::cerr << "Fiald to accept socket" << std::endl;
        exit(EXIT_FAILURE);
    }
    std::cout << "a client connected" << std::endl;

    char buffer[1024] = { 0 };
    // 读取数据  
	recv(new_socket, buffer, 1024, 0);
	std::cout << "Message from client: " << buffer << std::endl;
    
    const char* hello = "hello from server";
    // 发送响应  
    send(new_socket, hello, strlen(hello), 0);
    std::cout << "Hello message sent\n";

    // 关闭socket  
    closesocket(new_socket);
    closesocket(server_fd);

    // 清理Winsock  
    WSACleanup();

    return 0;
}

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐