我刚刚开始学习SFML网络....我正在制作一个服务器客户端聊天框...当我在PC上运行客户端程序时,它连接到也在我的PC上运行的服务器.....但是问题是我的笔记本电脑上的客户端程序没有连接到我的PC上的服务器程序....这是服务器的代码:
void main()
{
cout << "Server Running" << endl;
TcpListener listener;
SocketSelector selector;
bool done = false;
vector<TcpSocket*>clients;
listener.getLocalPort();
listener.listen(2000);
selector.add(listener);
while (!done)
{
if (selector.wait())
{
if (selector.isReady(listener))
{
TcpSocket *socket = new TcpSocket;
listener.accept(*socket);
Packet packet;
string id;
string status;
if (socket->receive(packet) == Socket::Done)
packet >> id>>status;
cout << id << " has "<<status;
clients.push_back(socket);
selector.add(*socket);
}
else
{
for (int i = 0;i < clients.size();i++)
{
if (selector.isReady(*clients[i]))
{
Packet packet, sendpacket;
if (clients[i]->receive(packet) == Socket::Done)
{
string text;
packet >> text;
sendpacket << text;
for (int j = 0;j < clients.size();j++)
{
if (i != j)
{
clients[j]->send(sendpacket);
}
}
}
}
}
}
}
}
for (vector<TcpSocket*>::iterator it = clients.begin();it != clients.end();it++)
delete *it;
}
客户代码:
#include<SFML/Network.hpp>
#include<SFML/Graphics.hpp>
#include<iostream>
#include<string>
#include<vector>
#include<conio.h>
using namespace sf;
using namespace std;
void main()
{
IpAddress ip = IpAddress::getLocalAddress();
cout << ip << endl;
TcpSocket socket;
bool done = false;
string id;
string status = "connected";
string text = "";
cout << "Enter online id: ";
cin >> id;
socket.connect(ip, 2000);
Packet packet;
packet << id<< status;
socket.send(packet);
socket.setBlocking(false);
RenderWindow window(VideoMode(800, 600, 32), id);
vector<Text> chat;
Font font;
font.loadFromFile("Data/font.ttf");
while (window.isOpen())
{
Event event;
while (window.pollEvent(event))
{
switch (event.type)
{
case Event::Closed:
window.close();
break;
case Event::KeyPressed:
if (event.key.code == Keyboard::Escape)
{
text.clear();
}
else if (event.key.code == Keyboard::Return)
{
Packet packet;
packet << id + ":" + text;
socket.send(packet);
Text displaytext(text, font, 20);
displaytext.setColor(Color::Green);
chat.push_back(displaytext);
text = "";
}
break;
case Event::TextEntered:
if (event.text.unicode == '\b' && text.size() >0)
{
text.erase(text.size() - 1, 1);
}
else
text += event.text.unicode;
break;
}
}
Packet packet;
socket.receive(packet);
string temptext;
if (packet >> temptext)
{
Text displaytext(temptext, font, 20);
displaytext.setColor(Color::Blue);
chat.push_back(displaytext);
}
int i = 0;
for (i;i<chat.size();i++)
{
chat[i].setPosition(0, i * 20);
window.draw(chat[i]);
}
Text drawtext(text, font, 20);
drawtext.setColor(Color::Red);
drawtext.setPosition(0, i * 20);
window.draw(drawtext);
window.display();
window.clear();
}
}
我需要知道我的笔记本电脑客户端如何找到并连接到服务器(pc)?
答案 0 :(得分:0)
您需要获取服务器的IP地址。现在,您正在向客户端提供客户端IP地址,这将无法正常工作。
对于初学者来说,你可以查找它并对其进行硬编码,但从长远来看,你需要找到一种方法来使它更具动态性。
最后一件事:没有void main()
这样的事情。这是未定义的行为,摆脱它。使用有效的切入点,很可能您想使用int main()
。