创建并连接socket,chat

#include
#include
#include
#include
#include
#include

int main() {
    int serverSocket, newSocket;
    struct sockaddr_in serverAddress, clientAddress;
    socklen_t clientLength;

    // 创建套接字
    serverSocket = socket(AF_INET, SOCK_STREAM, 0);
    if (serverSocket == -1) {
        perror("Failed to create socket");
        exit(EXIT_FAILURE);
    }

    // 设置服务器地址
    serverAddress.sin_family = AF_INET;
    serverAddress.sin_addr.s_addr = INADDR_ANY;
    serverAddress.sin_port = htons(8080);

    // 绑定套接字到指定地址和端口
    if (bind(serverSocket, (struct sockaddr*)&serverAddress, sizeof(serverAddress)) == -1) {
        perror("Failed to bind");
        exit(EXIT_FAILURE);
    }

    // 监听连接请求
    if (listen(serverSocket, 5) == -1) {
        perror("Failed to listen");
        exit(EXIT_FAILURE);
    }

    printf("Server listening on port 8080...\n");

    // 接受连接请求并处理客户端
    while (1) {
        // 接受客户端连接请求,创建新的连接套接字
        clientLength = sizeof(clientAddress);
        newSocket = accept(serverSocket, (struct sockaddr*)&clientAddress, &clientLength);
        if (newSocket == -1) {
            perror("Failed to accept");
            exit(EXIT_FAILURE);
        }

        printf("Client connected\n");

        // 在这里可以使用新的连接套接字与客户端进行数据交换

        // 关闭连接套接字
        close(newSocket);
        printf("Client disconnected\n");
    }

    // 关闭监听套接字
    close(serverSocket);

    return 0;
}
 

你可能感兴趣的:(linux编程,c++)