gpt4 book ai didi

c++ - "MFC/C++ Socket programming.."如何连接服务器和客户端?

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:52:47 25 4
gpt4 key购买 nike

我用了一个MFC/C++套接字编程的代码,但是只有当我在同一台电脑上做服务器和客户端时它才有效,但是当我在不同的电脑上使用客户端时,它找不到服务器并且连接失败.我不知道我使用的服务器的本地 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com