我使用了MFC/C++套接字编程的代码,但只有当我在同一台PC上创建服务器和客户端时它才有效,但是当我在不同PC上使用客户端时,它无法找到服务器并且连接失败。 我不知道我使用的服务器的本地 IP 或代码是否有问题,请提供帮助:)!
以下代码是服务器端:-
#include <afx.h>
#include <afxext.h>
#include <afxsock.h>
#include <iostream>
using namespace std;
int main()
{
AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0);
AfxSocketInit();
CSocket serverSocket;
serverSocket.Create(3333);
serverSocket.Listen();
CSocket clientSocket;
while(serverSocket.Accept(clientSocket))
{
CString s;
while(s!="bye")
{
char msg[128];
if(clientSocket.Receive(msg, 128)<0)break;
s = msg;
cout<<"Client: "<<msg<<endl;
sprintf_s(msg, 128, "Your msg (%d letter) arrived successfully.",
strlen(msg));
clientSocket.Send(msg, 128);
if(s=="shutdown")exit(0);
}
clientSocket.Close();
}
return 0;
}
以下客户端代码:-
#include <afx.h>
#include <afxext.h>
#include <afxsock.h>
#include <iostream>
using namespace std;
int main()
{
AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0);
AfxSocketInit();
CSocket clientSocket;
clientSocket.Create();
if(clientSocket.Connect("192.168.1.2", 3333))
{
cout<<"Connected to server."<<endl;
CString s;
while(s!="bye" && s!="shutdown")
{
char msg[128];
cin.getline(msg, 128);
s = msg;
clientSocket.Send(msg, 128);
if(clientSocket.Receive(msg, 128)<0)break;
cout<<msg<<endl;
}
}
else
{
cout<<"Cannot find server."<<endl;
}
return 0;
}
最佳答案
尝试连接到客户端中的另一个服务器地址而不是当前的固定地址怎么样?
if(clientSocket.Connect("192.168.1.2", 3333))
附注最好在程序中设置地址和端口号等参数。
关于c++ - "MFC/C++ Socket programming.."如何连接服务器和客户端?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13883329/