In my Android App I'm using DatagramSockets to send messages to a server like this:
InetAddress address = InetAddress.getByName(host);
byte[] byteMessage = (" " + message + "\r\n##!!##").getBytes();
DatagramPacket packet = new DatagramPacket(byteMessage, byteMessage.length, address, port);
DatagramSocket socket = new DatagramSocket();
try
{
socket.send(packet);
}
finally
{
socket.close();
}
But only every N-1th packet is sent.
Meaning if I send 1 packet, nothing is sent. If I send the second, the first one gets send. If I send the third, the second gets send etc etc.
EDIT:
So after the first comments I a) got rid of the useless throw-statement b) tried not closing the socket after sending. It doesn't help.
So as an example for clarification: The following code works perfectly and I receive the package server-side. But it's obviously not a pretty solution...
InetAddress address = InetAddress.getByName(host);
byte[] byteMessage = (" " + message + "\r\n##!!##").getBytes();
DatagramPacket packet = new DatagramPacket(byteMessage, byteMessage.length, address, port);
DatagramSocket socket = new DatagramSocket();
try
{
socket.send(packet);
String emptyMessage = " ";
socket.send(new DatagramPacket(emptyMessage.getBytes(), emptyMessage.getBytes().length, address, port));
}
finally
{
socket.close();
}
I'm just sending a second "empty" message afterwards. I first tried sending an empty byte array, but that does not work.
Related
my programm is establishing a connection via multicastsocket between server and client. I want to send some informations to the client and then receive an answer from the client and print it out.
This works, but it always printing out the String infromation. Like it is still saved in the DatagramPacket and fill the String received with data from String information. So when i run the programm its always printing out "Server: received Message: Welcome to the Event Server"
System.out.println("Server is running...");
InetAddress infoChannel = InetAddress.getByName("225.5.6.6");
MulticastSocket info_socket = new MulticastSocket(3456);
info_socket.joinGroup(infoChannel);
String information = "Welcome to the Event Server ";
byte [] buffer = information.getBytes();
DatagramPacket info_packet = new DatagramPacket(buffer, buffer.length, infoChannel, 3456);
info_socket.send(info_packet);
System.out.println("Message send");
while(true) {
info_packet.setData(new byte[256]);
info_socket.receive(info_packet);
String received = new String(info_packet.getData(), info_packet.getOffset(), info_packet.getLength());
info_packet.setLength(info_packet.getLength());
System.out.println("Server: received Message: " + received);
}
CLient :
System.out.println("Client is waiting for Connection to Server...");
InetAddress infoChannel = InetAddress.getByName("225.5.6.6");
MulticastSocket info = new MulticastSocket(3456);
info.joinGroup(infoChannel);
byte[] buffer = new byte[350];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
info.receive(packet);
String recString = new String(buffer);
String[] lines = recString.split("#");
Arrays.stream(lines).forEach(System.out::println);
System.out.println("Enter message to send: ");
String answer = readIn.nextLine();
packet = new DatagramPacket(answer.getBytes(), answer.length(), infoChannel, 3456);
info.send(packet);
System.out.println("client: Inormation sended to Server");
info.close();
Thanks in advance!
i tried to somehow clear the buffer and then store the received message in the String received
This question already has answers here:
How to detect that UDP packet has been lost? (C#)
(5 answers)
Closed 2 years ago.
For a reliable connection you have to use TCP.
However, I would like to know if there is a way to modify my code so that I can check for lost packets in UDP
try {
DatagramSocket socket = new DatagramSocket(5000);
while(true) {
byte[] buffer = new byte[50];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
System.out.println("Text received is: " + new String(buffer, 0, packet.getLength()));
String returnString = "echo: " + new String(buffer, 0, packet.getLength());
byte[] buffer2 = returnString.getBytes();
InetAddress address = packet.getAddress();
int port = packet.getPort();
packet = new DatagramPacket(buffer2, buffer2.length, address, port);
socket.send(packet);
}
} catch(SocketException e) {
System.out.println("SocketException: " + e.getMessage());
} catch(IOException e) {
System.out.println("IOException: " + e.getMessage());
}
}
Since the transport protocol does not provide facilities, the application protocol needs to do so.
You could for example make the sender add a sequence number into each message, and the receiver would then know that a datagram had been lost, or (also possible) duplicated.
That lets you detect loss, but does nothing to allow you to recover from it.
You'd need in the receiver to track expected sequence numbers per sender, of course.
I try to read the UDP Stream from X-Plane 12 in Java.
This is what I try:
public class EchoClient {
#Test
public void echo() throws IOException {
DatagramSocket socket;
InetAddress address;
byte[] buf;
socket = new DatagramSocket();
address = InetAddress.getByName("localhost");
String msg = "TEST";
buf = msg.getBytes();
DatagramPacket packet
= new DatagramPacket(buf, buf.length, address, 49000);
socket.send(packet);
packet = new DatagramPacket(buf, buf.length);
System.out.println("hi there");
while(true) {
socket.receive(packet); // it "stops" here... without an error
String received = new String(
packet.getData(), 0, packet.getLength());
System.out.println(received);
}
}}
X-Plane is running and the UDP option is activated - but my program does print nothing on the console.. and it is runnig forever (while true)
Receive is blocked and waiting to a receive a packet. The packet you sent earlier is dropped on the floor because no one is listening.
It's my first post so it may be not well stylished but I tried...
So... I have two machines, both running Java. I want them to run something like this.
Client: sends multicast to listening servers.
Server(s): the server captures the multicast and sends a unicast back with name of local machine that server runs on.
Client: receives the unicast with the server adress(es) and makes a list with their hostnames.
But the client doesn't even send the multicast (I was watching wireshark capturing packets)
It only sends something when I put 230.0.0.1 as multicast address, but then, the server doesn't receive the packet.
EDIT: When I send a unicast packet to the server it responds fine.
Here is my code:
try
{
//The client runs on LeJOS EV3 so I used their classes a bit
LCDOutputStream lcd = new LCDOutputStream();
PrintStream p = new PrintStream(lcd);
while(true)
{
if(Button.waitForAnyPress() == Button.ID_ESCAPE)
{
break;
}
byte[] buf = this.writeString("get_ip");
DatagramSocket sender = new DatagramSocket();
DatagramPacket packet = new DatagramPacket(buf, buf.length, InetAddress.getByName("230.0.0.1"), 5555);
sender.send(packet);
sender.close();
p.println("Sent Multicast");
}
p.close();
lcd.close();
}
catch(Exception e)
{
console.printException(e);
}
Here is the server code:
MulticastSocket s = new MulticastSocket(5555);
s.joinGroup(InetAddress.getByName("225.1.1.1"));
while(true)
{
try
{
/*
* 225.1.100.1
*
DataSender.Impl.reply("225.1.100.1", 5555, InetAddress.getLocalHost().getHostName(), "get_ip");*/
byte[] buf = new byte[256];
DatagramPacket p = new DatagramPacket(buf, buf.length);
s.receive(p);
System.out.println("DEBUG: received request");
}
catch(IOException e)
{
e.printStackTrace();
break;
}
}
s.close();
The comments made by ecle in response to the following post helped me resolve a similar issue: Java Multicast sample program is unable to deliver packets within LAN (across hosts). In my case, adding setInterface(<server address>); worked. For example:
MulticastSocket s = new MulticastSocket(5555);
s.setInterface(<server address>);
s.joinGroup(InetAddress.getByName("225.1.1.1"));
How can broadcast a message from single server to multiple clients and listen for a reply from one of the clients.
I used Multicast Programming to broadcast the message to the clients. And If i send the message from one of my clients back to the server either through TCP or UDP, I am getting a "java.net.ConnectException: Connection refused: connect" exception.
Please help me out.
Thanks in Advance.
Sender Code :
// Broadcasting the message
msg = "This is multicast! " + counter;
counter++;
outBuf = msg.getBytes();
// Send to multicast IP address and port
InetAddress address = InetAddress.getByName("224.2.2.3");
outPacket = new DatagramPacket(outBuf, outBuf.length, address,
PORT);
socket.send(outPacket);
System.out.println("Server sends : " + msg);
socket.close();
// Receiving TCP
apSock = new Socket("131.151.88.165", 6161);
apBuffReader = new BufferedReader(new InputStreamReader(
apSock.getInputStream()));
while ((ap2Toap1 = apBuffReader.readLine()) != null) {
System.out.println(ap2Toap1);
}
Receiver Code :
count++;
inPacket = new DatagramPacket(inBuf, inBuf.length);
socket.receive(inPacket);
String msg = new String(inBuf, 0, inPacket.getLength());
System.out.println("From " + inPacket.getAddress() + " Msg : "
+ msg);
socket.close();
// Sending TCP
apSock = new Socket("131.151.88.165", 6161);
System.out.println("Hello2");
respWriter = new PrintWriter(apSock.getOutputStream());
System.out.println("Writing back to the server");
respWriter.println(outBuf);
if (respWriter != null)
respWriter.close();
There is no listening in your code. TCP listening in Java is accomplished via a ServerSocket. You aren't using one. Instead you're using Sockets at both ends. So what you have is two clients and no server. No communication is possible between two TCP clients.