1. 程式人生 > >socket聊天室

socket聊天室

原文地址:https://blog.csdn.net/xiaoquantouer/article/details/58001960

服務端

#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include <stdio.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")  //載入ws2_32.lib庫

int main(int argc, char *argv[])
{
    //載入套接字
    WORD sockVersion = MAKEWORD(2, 2);//指定socket版本2.2
WSADATA wsaData;//儲存被WSAStartup函式呼叫後返回的Windows Sockets資料 if (WSAStartup(sockVersion, &wsaData) != 0) return 0; //建立服務端socket,三個引數分別代表IP地址族,流式套接字,TCP協議 SOCKET slisten = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (slisten == INVALID_SOCKET) { printf("socket error!"); return
0; } //繫結服務端ip和埠 sockaddr_in sin;//存放了地址族、埠、ip地址,用來處理通訊地址 sin.sin_family = AF_INET;//ip地址族 sin.sin_port = htons(8888);//轉換網路編碼,偵聽本地8888埠 sin.sin_addr.S_un.S_addr = INADDR_ANY;//接收任意地址的連線 if (bind(slisten, (LPSOCKADDR)&sin, sizeof(sin)) == SOCKET_ERROR) { printf("bind error!"
); } //開始偵聽 if (listen(slisten, 5) == SOCKET_ERROR) { printf("listen error!"); return 0; } SOCKET sClient;//建立客戶端socket sockaddr_in remoteAddr;//客戶端的地址資訊 int nAddrlen = sizeof(remoteAddr); char revData[255];//接收資料緩衝區 //迴圈接收資料 while (1) { printf("waiting...\n"); //等待連線,返回客戶端socket sClient = accept(slisten, (SOCKADDR *)&remoteAddr, &nAddrlen); if (sClient == INVALID_SOCKET) { printf("accept error!"); continue; } printf("Connection successful:%s\n", inet_ntoa(remoteAddr.sin_addr)); //接收資料 int ret = recv(sClient, revData, 255, 0);//若無錯誤,返回讀入位元組數 if (ret > 0) { revData[ret] = '\0'; printf("%s\n", revData); } //傳送資料 char sendData[255]; gets_s(sendData); send(sClient, sendData, strlen(sendData), 0); closesocket(sClient); } closesocket(slisten);//關閉服務端socket WSACleanup(); return 0; }

客戶端

#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include<winsock2.h>  
#include<stdio.h>  
#pragma comment(lib, "ws2_32.lib")  

int main()
{
    WORD sockVersion = MAKEWORD(2, 2);
    WSADATA data;
    if (WSAStartup(sockVersion, &data) != 0) return 0;

    while (true) 
    {
        SOCKET sclient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
        if (sclient == INVALID_SOCKET)
        {
            printf("invalid socket!");
            return 0;
        }

        sockaddr_in serAddr;//處理服務端地址的結構,包含地址族、埠、ip地址
        serAddr.sin_family = AF_INET;//IP地址族
        serAddr.sin_port = htons(8888);//服務端埠
        serAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");//服務端ip

        if (connect(sclient, (sockaddr *)&serAddr, sizeof(serAddr)) == SOCKET_ERROR)
        {
            printf("connect error !");
            closesocket(sclient);
            return 0;
        }

        //傳送資料
        char sendData[255];
        gets_s(sendData);
        send(sclient, sendData, strlen(sendData), 0);   

        //接收資料
        char recData[255];
        int ret = recv(sclient, recData, 255, 0);
        if (ret>0) {
            recData[ret] = '\0';
            printf(recData);
        }
        closesocket(sclient);
    }

    WSACleanup();
    return 0;
}