I want to send data like device Ip Address over wifi....
For achieving goals i write the following code
public void run() {
try {
DatagramSocket socket = new DatagramSocket(DISCOVERY_PORT);
socket.setBroadcast(true);
socket.setSoTimeout(TIMEOUT_MS);
sendDiscoveryRequest(socket);
listenForResponses(socket);
} catch (IOException e) {
Log.e(TAG, "Could not send discovery request", e);
}
}
public void sendDiscoveryRequest(DatagramSocket socket) throws IOException {
String data = "Test Data";
Log.d(TAG, "Sending data " + data);
DatagramPacket packet = new DatagramPacket(data.getBytes(), data.length(),
getBroadcastAddress(), DISCOVERY_PORT);
socket.send(packet);
}
public void listenForResponses(DatagramSocket socket) throws IOException {
byte[] buf = new byte[1024];
try {
while (true) {
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
String s = new String(packet.getData(), 0, packet.getLength());
Log.d(TAG, "Received response " + s);
}
} catch (SocketTimeoutException e) {
Log.d(TAG, "Receive timed out");
}
}
InetAddress getBroadcastAddress()
{
try
{
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
DhcpInfo dhcp = wifi.getDhcpInfo();
// handle null somehow
int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
byte[] quads = new byte[4];
for (int k = 0; k < 4; k++)
quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
return InetAddress.getByAddress(quads);
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
But it return the Ip Address of the device where it is currently running....and receives the same data that it sends.....any way to send data and receive data to a wifi connected android device? Please help me with this...
Related
Is there any good option to send broadcast message on UDP port while receiving data from other devices on the same port?
I have this currently:
First I initialize 1 DiagramSocket for both reading and sending:
private void startSocket(){
try {
if(socket == null) {
socket = new DatagramSocket(3040);
socket.setBroadcast(true);
socket.setReuseAddress(true);
}
} catch (Exception e) {
e.printStackTrace();
}
}
In first Thread I have reading/receiving for current socket:
public class Server implements Runnable {
public Server(iBroadcastResponse iBResponse){
BroadcastClass.this.iBResponse = iBResponse;
}
#Override
public void run() {
startSocket();
while (DataHandler.isEmergencyMode.get() ) {
try {
byte[] buf = new byte[256];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
if(socket == null)
return;
socket.receive(packet);
String command = stringFromPacket(packet);
Log.d(TAG, command);
addToBroadcastCalls(command);
if(iBResponse != null)
iBResponse.onResponse();
} catch (Exception e) {
Log.e(TAG, "Server: Error!\n");
}
}
Log.e(TAG, "Stop!");
}
String stringFromPacket(DatagramPacket packet) {
return new String(packet.getData(), 0, packet.getLength());
}
}
If I run this, it works normally, reads receiving data. But if I try to send data in another thread:
socketThread = new Thread(){
#Override
public void run() {
startSocket();
String message = "Message";
byte[] buf = message.getBytes();
DatagramPacket packet = new DatagramPacket(buf, buf.length);
try {
if(!socket.isConnected())
socket.connect(InetAddress.getByName("255.255.255.255"), 3040);
if (socket != null) {
socket.send(packet);
}
Log.d(TAG, "Send: " +message);
} catch (Exception e) {
e.printStackTrace();
}
}
};
socketThread.start();
When .send() is called it stops receiving data from other devices so now it only send message but stops receiving it from other devices.
Is there any good solution to this problem?
This was the solution
https://stackoverflow.com/a/25520279/1088975
I only changed
System.log...
To
Log.w(TAG, "Message...");
And I changed IP to be always "255.255.255.255" instead of
getBroadcastAddress()
which returns broadcast IP for current WIFI, which didn't work on my android devices
Am trying to send data to particular ip address in particular port. but there is no response from the hardware device. below is my code. Same thing are work properly in iOS.but in androidd tt throwing socket timeout exception.
DatagramSocket sendSoc = null;
DatagramPacket packet = null;
try {
sendSoc = new DatagramSocket(WIPHONEPORT);//2739
sendSoc.setBroadcast(true);
sendSoc.setSoTimeout(5000);
InetSocketAddress address = new InetSocketAddress(InetAddress.getByName(deviceSignature.getDeviceIP()), WIPHONEPORT);
byte[] ip = object.ToBuffer();
Log.d("data", ip.length + "##" + Arrays.toString(ip));
packet = new DatagramPacket(ip,
ip.length, address.getAddress(), address.getPort());
} catch (IOException e) {
Log.d("error","could not able to send packet");
return;
}
WiphoneProp prop;
boolean canLoop = true;
int i = 0;
////////////
while (canLoop) {
try {
sendSoc.send(packet);
try {
byte buf[] = new byte[1024];
DatagramPacket pack = new DatagramPacket(buf, buf.length);
sendSoc.receive(pack);
if (pack.getData() != null) {
if (!pack.getAddress().equals(getLocalIp())) {
prop = new WiphoneProp(pack.getData());
prop.validate();
canLoop=false;
Log.d("bytearray", Arrays.toString(pack.getData()));
Log.d("address ", pack.getAddress().getHostAddress() + " ## " + pack.getAddress().getHostName() + " ## " + pack.getAddress().getCanonicalHostName());
Log.d("result", prop.getWiphoneName());
}
}
} catch (UnknownHostException e) {
Log.d("UnknownHostException", "UnknownHostException");
}
} catch (IOException e) {
Log.d("SocException", "IOException");
}
i++;
}
Please help me. If you are not clear comment here please.
I fixed this issue by using same DatagramSocket object for all request.
My Android app needs to know the ip of the machine running the server on my local network. My plan is to broadcast an UDP packet in my app and to send a packet back from the server, so the app know the ip.
This is my code on Android:
...
new SendUDPTask().execute();
...
/************ getBroadcastAddress: know where to send the signal to find the server ***********/
private InetAddress getBroadcastAddress() {
//setup
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
DhcpInfo dhcp = wifiManager.getDhcpInfo();
//complicated stuff
int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
byte[] quads = new byte[4];
for (int k = 0; k < 4; k++)
quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
//return result
InetAddress result = null;
try {
result = InetAddress.getByAddress(quads);
} catch (UnknownHostException e) {
e.printStackTrace();
}
return result;
}
/************ sendUDP: here e send the packet that will allow us to find the server ***********/
private DatagramPacket sendUDP(String req, int port) throws IOException {
DatagramSocket socket = new DatagramSocket(port);
socket.setBroadcast(true);
InetAddress broadcastAddress = getBroadcastAddress();
DatagramPacket packet = new DatagramPacket(req.getBytes(), req.length(), broadcastAddress, port);
socket.send(packet);
byte[] buf = new byte[1024];
packet = new DatagramPacket(buf, buf.length);
socket.setSoTimeout(3000);
//We wouldn't want to think our own message is the server's response
String myAddress = getMyAddress();
socket.receive(packet);
while (packet.getAddress().getHostAddress().contains(
myAddress))
{
socket.receive(packet);
}
socket.close();
return packet;
}
/***************************** getMyAddress: the device's address *****************************/
public String getMyAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress())
return inetAddress.getHostAddress();
}
}
}
catch (SocketException e) {
e.printStackTrace();
}
return null;
}
private class SendUDPTask extends AsyncTask<String, Void, DatagramPacket> {
private Exception exception;
protected DatagramPacket doInBackground(String... params) {
try {
DatagramPacket packet = sendUDP("Ping", 31415);
Log.d("GJ", packet.getAddress().getHostAddress().toString());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(DatagramPacket packet) {
}
}
This is my code on my computer (Node.js):
var PORT = 31415;
var HOST = '127.0.0.1';
var dgram = require('dgram');
var server = dgram.createSocket('udp4');
server.on('listening', function () {
var address = server.address();
console.log('UDP Server listening on ' + address.address + ':' + address.port);
});
server.on('message', function (message, remote) {
console.log(remote.address + ':' + remote.port + ' - ' + message);
});
server.bind(PORT, HOST);
I am not sending back anything yet, but I should see the console.log. I don't see anything, which must mean the packet didn't arrive.
Does anyone have an idea?
Thanks a lot
If you bind the socket to loopback (127.0.0.1) interface you won't receive messages broadcasted in the network (192.168.1.255 in this case). In the nodejs server bind the socket to INADDR_ANY.
Actually I want to write a program in which whenever a button is pressed on specific digital pin of Arduino, Android receives that signal using UDP and performs tasks accordingly.
This is the Arduino code snippet:
void loop() {
buttonState = digitalRead(12);
if (buttonState == HIGH) {
// ToDo when push button is pressed
}
else {
Udp.beginPacket(Udp.remoteIP(),Udp.remotePort());
Udp.write("anything here");
Udp.endPacket();
}
This is my Android code:
public class Server implements Runnable
{
String serverHostname1, serverHostname2;
DatagramSocket d1;
InetAddress ip, retiip;
DatagramPacket send, rec;
String modifiedSentence;
public static String TAG = "SERVER";
DatagramSocket serverSocket;
public void run() {
Log.d(TAG, "Service Started");
try {
serverSocket = new DatagramSocket(8032);
} catch (SocketException e) {
e.printStackTrace();
}
Log.d(TAG, "Service Started");
byte[] receiveData = new byte[1024];
while (true) {
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
Log.d(TAG, "Service Started");
try {
serverSocket.receive(receivePacket);
} catch (IOException e) {
e.printStackTrace();
}
String sentence = new String(receivePacket.getData());
System.out.println("RECEIVED: " + sentence);
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
Log.d(TAG, "Service Started");
Log.d(TAG, "Received " + sentence);
}
}
I'm trying to broadcast a audio file from my android device via udp to the local wifi and have the clients on the local network listen to it via VLC's network streaming option. I can broadcast it and recieve it on anydevice connected to the network if i use my own recieve code, But i want VLC to be able to play it. Is ther any specific encoding or formatting that needs to be done before I send the datagram packet?
My sending code
public void SendAudio()
{
Thread thrd = new Thread(new Runnable() {
#Override
public void run()
{
Log.e(LOG_TAG, "start send thread, thread id: "
+ Thread.currentThread().getId());
long file_size = 0;
int bytes_read = 0;
int bytes_count = 0;
File audio = new File(AUDIO_FILE_PATH);
FileInputStream audio_stream = null;
file_size = audio.length();
byte[] buf = new byte[BUF_SIZE];
try
{
InetAddress addr = InetAddress.getByName("192.168.1.255");
DatagramSocket sock = new DatagramSocket();
while(true){
bytes_count=0;
audio_stream = new FileInputStream(audio);
while(bytes_count < file_size)
{
bytes_read = audio_stream.read(buf, 0, BUF_SIZE);
DatagramPacket pack = new DatagramPacket(buf, bytes_read,
addr, AUDIO_PORT);
sock.send(pack);
bytes_count += bytes_read;
Log.d(LOG_TAG, "bytes_count : " + bytes_count);
Thread.sleep(SAMPLE_INTERVAL, 0);
}
}
}
catch (InterruptedException ie)
{
Log.e(LOG_TAG, "InterruptedException");
}
catch (FileNotFoundException fnfe)
{
Log.e(LOG_TAG, "FileNotFoundException");
}
catch (SocketException se)
{
Log.e(LOG_TAG, "SocketException");
}
catch (UnknownHostException uhe)
{
Log.e(LOG_TAG, "UnknownHostException");
}
catch (IOException ie)
{
Log.e(LOG_TAG, "IOException");
}
} // end run
});
thrd.start();
}
My Recieving Code`
public void RecvAudio()
{
Thread thrd = new Thread(new Runnable() {
#Override
public void run()
{
Log.e(LOG_TAG, "start recv thread, thread id: "
+ Thread.currentThread().getId());
AudioTrack track = new AudioTrack(AudioManager.STREAM_MUSIC,
SAMPLE_RATE, AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT, BUF_SIZE,
AudioTrack.MODE_STREAM);
track.play();
try
{
DatagramSocket sock = new DatagramSocket(AUDIO_PORT);
byte[] buf = new byte[BUF_SIZE];
while(true)
{
DatagramPacket pack = new DatagramPacket(buf, BUF_SIZE);
sock.receive(pack);
Log.d(LOG_TAG, "recv pack: " + pack.getLength());
track.write(pack.getData(), 0, pack.getLength());
}
}
catch (SocketException se)
{
Log.e(LOG_TAG, "SocketException: " + se.toString());
}
catch (IOException ie)
{
Log.e(LOG_TAG, "IOException" + ie.toString());
}
} // end run
});
thrd.start();
}
Once again, using this i can send this from one android device and listen from another just fine using the recieve code ive given, but i want to play it using vlc's get network stream command and listen to h77p://#:port and get the audio playing.
Tnx again :)
You can use the code from this tutorial:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audio.setMode(AudioManager.MODE_IN_COMMUNICATION);
AudioGroup audioGroup = new AudioGroup();
audioGroup.setMode(AudioGroup.MODE_NORMAL);
AudioStream audioStream = new AudioStream(InetAddress.getByAddress(getLocalIPAddress ()));
audioStream.setCodec(AudioCodec.PCMU);
audioStream.setMode(RtpStream.MODE_NORMAL);
//set receiver(vlc player) machine ip address(please update with your machine ip)
audioStream.associate(InetAddress.getByAddress(new byte[] {(byte)192, (byte)168, (byte)1, (byte)19 }), 22222);
audioStream.join(audioGroup);
} catch (Exception e) {
Log.e("----------------------", e.toString());
e.printStackTrace();
}
}
public static byte[] getLocalIPAddress () {
byte ip[]=null;
try {
for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
ip= inetAddress.getAddress();
}
}
}
} catch (SocketException ex) {
Log.i("SocketException ", ex.toString());
}
return ip;
}