问题遇到的现象和发生背景
弄了一个云服务器,想练习一下SOCKET、TCP,然后就找了个教程试了一下,但是一摸一样的程序,为什么我就不能链接我的公网?是还需要在云服务器上配置什么吗?
用代码块功能插入代码,请勿粘贴截图
#include<stdio.h>
#include<string>
#include<WinSock2.h>
#include<windows.h>
using namespace std;
#pragma comment(lib,"ws2_32.lib")
#define SERVER_IP "87.167.59.188"
#define QUN_LIAO_PORT 9999
SOCKET serverSocket;
sockaddr_in sockAddr;
char nickName[32];//昵称
// GBK编码转换到UTF8编码
void GBKToUTF8(string& strGBK)
{
int len = MultiByteToWideChar(CP_ACP, 0, strGBK.c_str(), -1, NULL, 0);
wchar_t* wszUtf8 = new wchar_t[len];
memset(wszUtf8, 0, len );
MultiByteToWideChar(CP_ACP, 0, strGBK.c_str() ,- 1, wszUtf8, len);
len = WideCharToMultiByte(CP_UTF8, 0, wszUtf8, -1, NULL, 0, NULL, NULL);
char* szUtf8 = new char[len + 1];
memset(szUtf8, 0, len + 1);
WideCharToMultiByte(CP_UTF8, 0, wszUtf8, -1, szUtf8, len, NULL, NULL);
strGBK = szUtf8;
delete[]szUtf8;
delete[]wszUtf8;
}
bool init() {
//初始化
WSADATA data;
int ret =WSAStartup(MAKEWORD(1, 1), &data);
if (ret!= 0) {
return false;
}
//网络套接字
SOCKET serverSocket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
//物理地址
sockAddr.sin_family = PF_INET;
sockAddr.sin_addr.S_un.S_addr = inet_addr(SERVER_IP);
sockAddr.sin_port = htons(QUN_LIAO_PORT);
return true;
}
void login() {
system("mode con lines=5 cols=30\n");
printf("大连东软信息学院\n\n");
printf(" 昵称");
scanf_s("%s,",nickName, sizeof(nickName));
while (getchar() != '\n');//清缓存
string name = nickName;
GBKToUTF8(name);
send(serverSocket, name.c_str(), strlen(name.c_str()) + 1, 0);
}
int main(void) {
if (!init() ){
printf("初始化失败!\n");
return -1;
}
int ret =connect(serverSocket, (SOCKADDR*)&sockAddr, sizeof(sockAddr));
if (ret != 0) {
printf("链接服务器失败!\n");
return -2;
}
//登录聊天
login();
return 0;
}
运行结果及报错内容
我的解答思路和尝试过的方法
打开云端防火墙
我想要达到的结果
能连上公网就好