Linux 下 C++ Socket编程 服务器端

#include 
#include 
#include 
#include 
#include 
using namespace std;

#define MYPORT 3456    //服务器监听端口号

int main()
{
    cout << "服务器启动中~" << endl;
    sockaddr_in Server_addr;
    sockaddr_in Client_addr;
    int Socket_Server = socket(AF_INET, SOCK_STREAM, 0);
    int Socket_Client;
    if(Socket_Server == -1)
    {
        cerr<<"Socket创建失败!!!"<return -1;
    }
    memset(&Server_addr, 0, sizeof(Server_addr));
    Server_addr.sin_family = AF_INET;
    Server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    Server_addr.sin_port = htons(MYPORT);
    if(bind(Socket_Server, (sockaddr *)(&Server_addr),sizeof(sockaddr)) == -1)
    {
        cerr<<"Bind失败!!!"<return -1;
    }
    if(listen(Socket_Server, 10) == -1)
    {
        cerr<<"监听失败!!!"<return -1;
    }
    unsigned int sin_size = sizeof(sockaddr_in);
    Socket_Client = accept(Socket_Server, (sockaddr *)&Client_addr, &sin_size);
    if(Socket_Client == -1)
    {
        cerr<<"连接失败!!!"<return -1;
    }
    cout<<"客户端已连接~"<string str;
    char Buffer[1000];
    while(true)
    {
        memset(Buffer, 0, sizeof(Buffer));
        int Str_Len = read(Socket_Client, Buffer, 1000);
        if(strcmp(Buffer, "exit")==0 || Str_Len <= 0)
            break;
        cout<<"收到:\t"<< Buffer <cout<<"发送:\t";
        getline(cin, str);
        strcpy(Buffer,str.c_str());
        send(Socket_Client, Buffer, sizeof(Buffer), 0);
    }
    cout<<"客户端已退出,关闭服务器"<return 0;
}

你可能感兴趣的:(C++,Linux)