0

I have android device

This code I send message to server:

DatagramPacket sentPacket = new DatagramPacket(MESSAGE.getBytes(), MESSAGE.length(), getBroadcastAddress(), DISCOVERY_PORT); 
mSocket.send(sentPacket);

This code I receive message from server:

    receivedPacket = new DatagramPacket(buffer, buffer.length);
    mSocket.receive(receivedPacket);

Everything works nice, but sometime I receive message that I sent before. But server shows correct sent data.

Does somebody know about this issue?

user1711993
  • 271
  • 4
  • 20

2 Answers2

0

You are broadcasting the packet, so you are picking it back up through the network interface.

Did you try filtering received packets based on the source IP? (If the source IP is yourself, packet is discarded)

See this question for more info.

EDIT: For your case:

receivedPacket = new DatagramPacket(buffer, buffer.length);
mSocket.receive(receivedPacket);

String sourceIp = receivedPacket.getAddress().getHostAdress();
if(sourceIp != myIp) handle(receivedPacket);
Community
  • 1
  • 1
Robin Eisenberg
  • 1,836
  • 18
  • 26
-1

Do you have to use sockets?

Why not using GCM? enter link description here

Its the best for android solutions. I tried to implement it with sockets but had many problems. For example, you will have to make a service, and set an ungoing notification to persiste the service in memory.

Nacho
  • 2,057
  • 2
  • 23
  • 32
  • What if we are talking about a client/server application over LAN? Then GCM is not a solution. GCM is NOT a drop-in replacement for sockets, at all. – Robin Eisenberg Jul 10 '14 at 15:03
  • @RobinEisenberg ok! Thats why i asked if you had to use sockets. In my case, i had to implement communication in a LAN too. The sockets gave me problems with concurrency and muliple users (Don't know if that applies to you) and I decided to go with an ugly solution (but works like a charm), that is a service class with a thread polling messages with webservices. – Nacho Jul 10 '14 at 15:15
  • Actually if you thread it correctly I see no reason why I would recommend not using sockets. The difficulty is in concurrent access and threading correctly. If these are done well, there is nothing stopping you from communicating over Socket in Android. However, unsign the GCM in this case means your messages go through WAN layers when they do not need to. From a performance standpoint, that costs. – Robin Eisenberg Jul 10 '14 at 15:20
  • Because sockets require an open connection. And the server to manage all the connections. Its a poll method too... So i went to WS for make it easier. – Nacho Jul 10 '14 at 15:23