1. 程式人生 > >不用vs,c 語言windows下編寫socket,用gcc編譯

不用vs,c 語言windows下編寫socket,用gcc編譯

  • windows下socket一般都要vs,因為socket執行庫可能在win-sdk裡
    反正在system32裡我沒找到ws2.32.lib,因此需要下載一份這個,如果能在其他地方找到也可以,點選這裡可以WS2.32下載我上傳到雲盤裡的檔案,密碼:10nc。

  • 首先寫兩份程式碼,client.cpp, server.cpp

    client.cpp

#include <iostream>
#include <winsock2.h>

using namespace std;

#pragma comment(lib, "ws2_32.lib")

#define PORT 4000
#define IP_ADDRESS "127.0.0.1" int main(int argc, char * argv[]) { WSADATA Ws; SOCKET ClientSocket; struct sockaddr_in ServerAddr; int Ret = 0; int AddrLen = 0; HANDLE hThread = NULL; char SendBuffer[MAX_PATH]; //Init Windows Socket if ( WSAStartup(MAKEWORD(2,2), &Ws) != 0
) { cout<<"Init Windows Socket Failed::"<<GetLastError()<<endl; return -1; } //Create Socket ClientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if ( ClientSocket == INVALID_SOCKET ) { cout<<"Create Socket Failed::"<<GetLastError()<<endl; return
-1; } ServerAddr.sin_family = AF_INET; ServerAddr.sin_addr.s_addr = inet_addr(IP_ADDRESS); ServerAddr.sin_port = htons(PORT); memset(ServerAddr.sin_zero, 0x00, 8); Ret = connect(ClientSocket,(struct sockaddr*)&ServerAddr, sizeof(ServerAddr)); if ( Ret == SOCKET_ERROR ) { cout<<"Connect Error::"<<GetLastError()<<endl; return -1; } else { cout<<"連線成功!"<<endl; } while ( true ) { cin.getline(SendBuffer, sizeof(SendBuffer)); Ret = send(ClientSocket, SendBuffer, (int)strlen(SendBuffer), 0); if ( Ret == SOCKET_ERROR ) { cout<<"Send Info Error::"<<GetLastError()<<endl; break; } } closesocket(ClientSocket); WSACleanup(); return 0; }

server.cpp

//Server.cpp
#include <iostream>
#include <winsock2.h>

using namespace std;

#pragma comment(lib, "ws2_32.lib")

#define PORT 4000
#define IP_ADDRESS "127.0.0.1"


DWORD WINAPI ClientThread(LPVOID lpParameter)
{
    SOCKET CientSocket = (SOCKET)lpParameter;
    int Ret = 0;
    char RecvBuffer[1024];

    while ( true )
    {
        memset(RecvBuffer, 0x00, sizeof(RecvBuffer));
        Ret = recv(CientSocket, RecvBuffer, 1024, 0);
        if ( Ret == 0 || Ret == SOCKET_ERROR )
        {
            cout<<"客戶端退出!"<<endl;
            break;
        }
        cout<<"接收到客戶資訊為:"<<RecvBuffer<<endl;
    }

    return 0;
}

int main(int argc, char* argv[])
{
    WSADATA  Ws;
    SOCKET ServerSocket, ClientSocket;
    struct sockaddr_in LocalAddr, ClientAddr;
    int Ret = 0;
    int AddrLen = 0;
    HANDLE hThread = NULL;

    //Init Windows Socket
    if ( WSAStartup(MAKEWORD(2,2), &Ws) != 0 )
    {
        cout<<"Init Windows Socket Failed::"<<GetLastError()<<endl;
        return -1;
    }

    //Create Socket
    ServerSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if ( ServerSocket == INVALID_SOCKET )
    {
        cout<<"Create Socket Failed::"<<GetLastError()<<endl;
        return -1;
    }

    LocalAddr.sin_family = AF_INET;
    LocalAddr.sin_addr.s_addr = inet_addr(IP_ADDRESS);
    LocalAddr.sin_port = htons(PORT);
    memset(LocalAddr.sin_zero, 0x00, 8);

    //Bind Socket
    Ret = bind(ServerSocket, (struct sockaddr*)&LocalAddr, sizeof(LocalAddr));
    if ( Ret != 0 )
    {
        cout<<"Bind Socket Failed::"<<GetLastError()<<endl;
        return -1;
    }
    //listen
    Ret = listen(ServerSocket, 10);
    if ( Ret != 0 )
    {
        cout<<"listen Socket Failed::"<<GetLastError()<<endl;
        return -1;
    }

    cout<<"服務端已經啟動"<<endl;

    while ( true )
    {
        AddrLen = sizeof(ClientAddr);
        ClientSocket = accept(ServerSocket, (struct sockaddr*)&ClientAddr, &AddrLen);
        if ( ClientSocket == INVALID_SOCKET )
        {
            cout<<"Accept Failed::"<<GetLastError()<<endl;
            break;
        }

        cout<<"客戶端連線::"<<inet_ntoa(ClientAddr.sin_addr)<<":"<<ClientAddr.sin_port<<endl;

        hThread = CreateThread(NULL, 0, ClientThread, (LPVOID)ClientSocket, 0, NULL);
        if ( hThread == NULL )
        {
            cout<<"Create Thread Failed!"<<endl;
            break;
        }

        CloseHandle(hThread);
    }

    closesocket(ServerSocket);
    closesocket(ClientSocket);
    WSACleanup();

    return 0;
}

ok ,現在我們開始編譯:

  1. 你需要有window的gun的gcc,g++編譯器,沒有的話自行下載 MinGW
  2. 讓cmd到你當前兩個檔案和ws2.32所在目錄:
    分別執行命令 g++ -o server server.cpp -L ./ -lWS2_32
    g++ -o client client.cpp -L ./ -lWS2_32
    -L ./ 表示路勁 -l 表示動態庫的名稱

                        注意路勁,不然會出錯 。
    

    3.在當前cmd 執行server, 再開啟一個cmd執行client,ok。