visual c ++ winSock连接到vps,vds服务器,客户端和服务器等待连接,如何解决?

时间:2019-10-13 09:30:31

标签: c winsock

visual c ++ winSok作为客户端连接到vds,vps服务器(_____- ip)。 您好,问题是这样的:我正在编写一个应用程序,它应该可以通过Internet运行。因此,您需要一个应用程序应该连接到的服务器(物理服务器和软件服务器)(实际上,我购买了带有专用ip的机载单元),并且在测试期间,尝试调试时,并不清楚。决定像聊天一样编写一个测试应用程序。 并且当您尝试时,连接根本不会发生,也就是说,根本没有显示诸如“您的客户端(套接字:)”和“您的服务器(套接字:”)之类的消息。这可能是问题所在?

#include "pch.h"
#pragma comment(lib, "ws2_32.lib")

#include <cmath>
#include <winsock2.h>

#pragma warning(disable: 4996)

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

#include "windows.h"
#include "iostream"
#include "dos.h"
#include "stdio.h"
#include "winuser.h"
#include "Windef.h"
#include <fstream>
#include <thread>>
SOCKET h;

SOCKET createServer(const char * ip, long port) //function init socket: conection colient 
{
    SOCKET client;
    SOCKET connectRecept;//socket for litening conection client
    SOCKADDR_IN dataC;
    int sizeofData = sizeof(dataC); //to use in accept and init data socket
    dataC.sin_addr.s_addr = inet_addr(ip);
    dataC.sin_port = htons(port);
    dataC.sin_family = AF_INET;
    connectRecept = socket(AF_INET, SOCK_STREAM, NULL); //init socket
    bind(connectRecept, (SOCKADDR*)&dataC, sizeofData);
    listen(connectRecept, 1);
    client = accept(connectRecept, (SOCKADDR*)&dataC, &sizeofData);
    return client;
}


SOCKET conectTo(const char * ip, long port)//function conection to server(return socket)
{
    SOCKET server;
    SOCKADDR_IN dataC;
    int sizeofData = sizeof(dataC); //to use in init data socket
    dataC.sin_addr.s_addr = inet_addr(ip);
    dataC.sin_port = htons(port);
    dataC.sin_family = AF_INET;
    server = socket(AF_INET, SOCK_STREAM, NULL); //init socket
    bind(server, (SOCKADDR*)&dataC, sizeof(dataC));
    if (connect(server, (SOCKADDR*)&dataC, sizeof(dataC)) != 0) { //conect to server
    }
    return server;
}
int main()
{
    WSAData wsaData;
    WORD DLLVersion = MAKEWORD(2, 1);
    if (WSAStartup(DLLVersion, &wsaData) != 0) {
        std::cout << "Error" << std::endl;
        exit(1);
    }
    char f[40] = { "" };
    std::cin >> f;
    char mess[41] = { "" };

    if (!strcmp(f, "cl")) {
        h = conectTo("________", 1297);
        std::cout << "You client (socket : "<< h << ")\n";
        while (true)
        {
            std::cout << "Write your Messaage:";
            std::cin >> mess;
            send(h, mess, sizeof(char) * 40, NULL);
            recv(h, mess, sizeof(char) * 40, NULL);
            std::cout <<"Server say:" << mess;
        }
    }
    else {
        h = createServer("________", 1297);
        std::cout << "You server (socket : " << h << ")\n";
        while (true)
        {
            recv(h, mess, sizeof(char) * 40, NULL);
            std::cout << "Client" << mess;
            std::cin >> mess;
            std::cout << "Write your Messaage:";
            send(h, mess, sizeof(char) * 40, NULL);
        }
    }

}

0 个答案:

没有答案