简体   繁体   中英

UDP message not being received on server port

I am attempting to implement a server - client relationship, all on my local machine.

I have a java program acting as the server, which listens on port 4567. I have a java program acting as the client, which opens a connection to 127.0.0.1:4567 and sends messages.

This all works, messages are being received .

Problem

I implemented the client program in C++ using boost asio to send messages the same way, but it does not work, despite the fact that the message is being sent successfully.

C++ client code that does not work :

    using namespace boost::asio;
    io_service io_service;
    ip::udp::socket socket(io_service);
    ip::udp::endpoint remote_endpoint;

    socket.open(ip::udp::v4());

    remote_endpoint = ip::udp::endpoint(ip::address::from_string("127.0.0.1"), 4567);

    boost::system::error_code err;
    string msg = err.message();

    socket.send_to(buffer("test_from_c++", 13), remote_endpoint, 0, err);

    msg = err.message();
    cout << err.message() << endl;

    socket.close();

Output is

The operation completed successfully

Also, here is the java client code that works .

String address = "127.0.0.1";
int port = 4567;
Socket socket = new Socket(address, port);
System.out.println("Successfully opened socket for communication to " + address + " on port " + port);

BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
out.write("test_from_java");
out.newLine();

out.close();
socket.close();

The C++ code is correctly sending a UDP message. See here for a demonstration.

The issue is likely that the server is expecting a TCP connection and will not receive data that is using a different transport protocol. The Java client is using the java.net.Socket class which provides TCP communication. On the other hand, the java.net.DatagramSocket class is used for UDP communication.

Here is an equivalent TCP client demonstrated :

#include <iostream>
#include <boost/asio.hpp>

int main()
{
  using namespace std;
  using namespace boost::asio;
  io_service io_service;
  ip::tcp::socket socket(io_service);
  ip::tcp::endpoint remote_endpoint;

  remote_endpoint = ip::tcp::endpoint(ip::address::from_string("127.0.0.1"), 4567);
  socket.connect(remote_endpoint);

  boost::system::error_code err;
  string msg = err.message();

  socket.send(buffer("test_from_c++", 13), 0, err);

  msg = err.message();
  cout << err.message() << endl;

  socket.close();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM