客户端代码

Posted on 2024-09-07 09:48  封魔NJ  阅读(7)  评论(0编辑  收藏  举报
//客户端 
#include "mysocket.h"
//头文件 
using namespace std;

int main()
{
    cout<<"-------------------客户端---------------\n";
    startup();
    //填充服务端:这里填和服务端一样的就好,不做解释
    SOCKET client = createSocket(PF_INET, SOCK_STREAM);
    SOCKADDR_IN server_addr;
    server_addr.sin_family=AF_INET;
    string ip;
    cin>>ip;
    char ipconfig[ip.size()];
    for(int i=0;i<ip.size();i++){
        ipconfig[i]=ip[i];
    }
    server_addr.sin_addr.S_un.S_addr=inet_addr(ipconfig);
    server_addr.sin_port = htons(12345);
    //发送连接请求,请求连接原因
    if(connect(client,(SOCKADDR*)&server_addr,sizeof(SOCKADDR)) == SOCKET_ERROR){
        cout<<"连接错误!"<<endl;
        WSACleanup();
        return -1;
    }
    cout<<"成功连接服务器"<<endl;
    char send_buf[1145],recv_buf[4514];
    while(1){
        cout<<"输出要发送的信息:";
        cin>>send_buf;
        mysend(client,send_buf);
        cout<<"等待服务器响应...\n";
        myrecv(client,recv_buf);
        cout<<"收到来自服务器的信息:"<<recv_buf<<endl;
    } 
    return 0;
}