SFML udp通信实例

258 篇文章 9 订阅

包含的lib库文件,免得一个一个复制名称:

sfml-window-d.lib
sfml-system-d.lib
sfml-audio-d.lib
sfml-graphics-d.lib
sfml-main-d.lib
sfml-network-d.lib
vorbis.lib
vorbisenc.lib
vorbisfile.lib

void runUdpClient(unsigned short port)
{
    // Ask for the server address
    sf::IpAddress server;
    do
    {
        std::cout << "Type the address or name of the server to connect to: ";
        std::cin >> server;
    } while (server == sf::IpAddress::None);

    // Create a socket for communicating with the server
    sf::UdpSocket socket;

    // Send a message to the server
    const char out[] = "Hi, I'm a client";
    if (socket.send(out, sizeof(out), server, port) != sf::Socket::Done)
        return;
    std::cout << "Message sent to the server: \"" << out << "\"" << std::endl;

    // Receive an answer from anyone (but most likely from the server)
    char in[128];
    std::size_t received;
    sf::IpAddress sender;
    unsigned short senderPort;
    if (socket.receive(in, sizeof(in), received, sender, senderPort) != sf::Socket::Done)
    {
        return;
    }
        
    std::cout << "Message received from " << sender << ": \"" << in << "\"" << std::endl;
}

using namespace sf;
void runUdpPackageClient()
{
    // Ask for the server address
    IpAddress adress("localhost");

    // Create a socket for communicating with the server
    sf::UdpSocket socket;

    Packet sendpacket;
    sendpacket << "ceshishuju";
    socket.send(sendpacket, adress, 1028);

    IpAddress remoteAddress;
    unsigned short remotePort;
    Packet packet;
    if (socket.receive(packet, remoteAddress, remotePort) != sf::Socket::Done)
    {
        return;
    }
    int yyyy = 666;
}

测试使用SocketTool.exe工具即可

  • 11
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值