我用c++(socket)創了server和client兩個檔案, 在自己電腦裡能接收到client的回應
畢竟是自己的電腦, 但是把client傳給別人後卻收不到回應, 防火牆都有關
請問是為甚麼呢?
**server
#include <stdio.h>
#include <WinSock2.h>
#include <iostream>
#pragma comment (lib, "ws2_32.lib")
using namespace std;
int main()
{
//初始化網路
WSADATA wd;
WSAStartup(MAKEWORD(2, 2), &wd);
//創建套接字
SOCKET sockServ = socket(AF_INET, SOCK_STREAM, 0); //ipv4
SOCKADDR_IN addrServ;
addrServ.sin_family = AF_INET;
addrServ.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
addrServ.sin_port = htons(10010);
bind(sockServ, (SOCKADDR*)&addrServ, sizeof(SOCKADDR));
//監聽
listen(sockServ, 5);
while (true)
{
//接受客戶端請求
SOCKADDR_IN addrClient;
int length = sizeof(addrClient);
SOCKET sockColn = accept(sockServ, (SOCKADDR*)&addrClient, &length);
cout << inet_ntoa(addrClient.sin_addr)<<endl;
cout<<addrClient.sin_port;
}
WSACleanup();
return 0;
}
**client
#include <stdio.h>
#include <WinSock2.h>
#pragma comment (lib, "ws2_32.lib")
int main()
{
//初始化網路
WSADATA wd;
WSAStartup(MAKEWORD(2, 2), &wd);
//創建套接字
SOCKET sockClien = socket(AF_INET, SOCK_STREAM, 0);
SOCKADDR_IN addrServ;
addrServ.sin_family = AF_INET;
//server電腦IP: 192.168.77.195
addrServ.sin_addr.S_un.S_addr = inet_addr("192.168.77.195");
addrServ.sin_port = htons(10010);
connect(sockClien, (SOCKADDR*)&addrServ, sizeof(SOCKADDR));
WSACleanup();
return 0;
}
可以先把程式碼中加入除錯/錯誤處理 基礎功能
透過處理 WSAAccept 傳回值 擷取errorCode
**server
#include <stdio.h>
#include <WinSock2.h>
#include <iostream>
#pragma comment (lib, "ws2_32.lib")
using namespace std;
int main()
{
//初始化網路
WSADATA wd;
WSAStartup(MAKEWORD(2, 2), &wd);
//創建套接字
SOCKET sockServ = socket(AF_INET, SOCK_STREAM, 0); //ipv4
SOCKADDR_IN addrServ;
addrServ.sin_family = AF_INET;
addrServ.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
addrServ.sin_port = htons(10010);
bind(sockServ, (SOCKADDR*)&addrServ, sizeof(SOCKADDR));
//監聽
listen(sockServ, 5);
while (true)
{
//接受客戶端請求
SOCKADDR_IN addrClient;
int length = sizeof(addrClient);
SOCKET sockColn = WSAAccept(sockServ, (SOCKADDR*)&addrClient, &length, NULL, NULL);
if (sockColn == INVALID_SOCKET)
{
//處理 WSAAccept 傳回值的基礎用法
int errorCode = WSAGetLastError();
cout << "Error occurred during WSAAccept: " << errorCode << endl;
}
else
{
cout << inet_ntoa(addrClient.sin_addr)<<endl;
cout<<addrClient.sin_port;
}
}
WSACleanup();
return 0;
}
**client
#include <stdio.h>
#include <WinSock2.h>
#pragma comment (lib, "ws2_32.lib")
int main()
{
//初始化網路
WSADATA wd;
WSAStartup(MAKEWORD(2, 2), &wd);
//創建套接字
SOCKET sockClien = socket(AF_INET, SOCK_STREAM, 0);
SOCKADDR_IN addrServ;
addrServ.sin_family = AF_INET;
//server電腦IP: 192.168.77.195
addrServ.sin_addr.S_un.S_addr = inet_addr("192.168.77.195");
addrServ.sin_port = htons(10010);
if(connect(sockClien, (SOCKADDR*)&addrServ, sizeof(SOCKADDR)) == INVALID_SOCKET)
{
printf("Connect error: %d\n", WSAGetLastError());
WSACleanup();
return -1;
}
WSACleanup();
return 0;
}
程式需要正確的原始程式碼才能輕鬆啟動並運行。 這真是令人著迷。 我順著線索看了下去,發現其中的知識很有趣。 該解決方案也很容易修復錯誤 basketbros