I am trying to make an application to control DMX Channels. For this I have an ESP8266 which takes a String as an input like "2.255", where the first integer is the DMX Channel and the second integer the value.
For my PC I wrote a method that first builds the string and then sens it to the IP Address of the ESP8266 via a Socket.
for(DMXChannel c : list){
if(lastvalue.get(c.getChannelID() - 1) != c.getValue()){
try {
String msg = c.getChannelID() + "." + c.getValue();;
DatagramSocket clientSocket = new DatagramSocket();
InetAddress ipaddr = InetAddress.getByName(ip); //IP Address is "192.168.4.1"
byte[] sendData = new byte[1024];
sendData = msg.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ipaddr, 8888);
clientSocket.send(sendPacket);
clientSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
This works fine but I have a problem when I am trying to do a fade. The frequency of this piece of code seems to be too slow.
Does anyone have a "faster" solution?
Here are some things you could do to speed up the code:
Do not call getByName for an IP address. This involves DNS, but DNS is not needed for an IP address. Instead call getByAddress. If you do need to call getByName, call it only once and cache the answer.
Do not open, close, reopen, etc. the socket each time. Just keep it open.
Related
My app is unable to receive the UDP packets when running in the emulator. UDP packets are sent by below java program on "localhost" over the port 49999.
DatagramSocket clientsocket;
DatagramPacket dp;
BufferedReader br;
InetAddress ia;
byte buf[] = new byte[1024];
int cport = 50000, sport = 49999;
clientsocket = new DatagramSocket(cport);
dp = new DatagramPacket(buf, buf.length);
br = new BufferedReader(new InputStreamReader(System.in));
ia = InetAddress.getLocalHost();
while(true)
{
Random rand = new Random();
String str1 = rand.nextInt(100) + "";
buf = str1.getBytes();
System.out.println("Sending " + str1);
clientsocket.send(new DatagramPacket(buf,str1.length(), ia, sport));
try{
Thread.sleep(100);
} catch(Exception e){}
}
Another java UDP server program running on the same localhost receives the packets fine. This means that the packets are sent to localhost:49999 correctly.
To forward the packets from localhost to the emulator, I did telnet redirect as below:
telnet localhost 49999
redir add udp:49999:49999
The UDP receiver in the app looks like this:
byte[] data = new byte[1400];
DatagramPacket packet = new DatagramPacket(data, 1400);
DatagramSocket socket = new DatagramSocket(49999);
socket.setSoTimeout(200);
try{
socket.receive(packet); ---->> This throws a SocketTimeoutException
} catch(SocketTimeoutException e){}
My understanding was that the telnet redirect should take care of forwarding the packets from my development machine's localhost:49999 to emulator's localhost:49999 so that the data is available on the DatagramSocket(49999). However it keeps throwing the SocketTimeoutException all the time.
It would be a great help to know what is the missing piece of the puzzle here.
After connecting to the localhost you may want to check that the port was actually asigned as intended with the command netstat -na in the cmd. It also might be worth a try to use the IP 127.0.0.1 instead.
i am using the below code to send text message between two android devices but i could not receive the packet at the receiver side
the sender:
String messageStr="Hello Android!";
Log.d("note","message prepaered");
int server_port = 12345;
try{
Log.d("note","socket prepaered");
DatagramSocket s = new DatagramSocket();
Log.d("note","socket defined");
InetAddress local = InetAddress.getByName(ip.getText().toString());
int msg_length=messageStr.length();
byte[] message = messageStr.getBytes();
Log.d("note","converting message to bytes");
DatagramPacket p = new DatagramPacket(message, msg_length,local,server_port);
s.send(p);
Log.d("note","sending msg");}
catch (SocketException e){
Log.d("error",e.getMessage());
}
catch(IOException v1){
Log.d("error", v1.getMessage());
}
the receiver :
String text;
int server_port = 12345;
byte[] message = new byte[1500];
try{
DatagramPacket p = new DatagramPacket(message, message.length);
Log.d("note","putting msg in packet");
DatagramSocket s = new DatagramSocket(server_port);
Log.d("note","defining socket");
s.receive(p);
Log.d("note","recieving packet");
text = new String(message, 0, p.getLength());
msg.setText(text);
s.close();
}
catch (SocketException e){
Log.d("error",e.getMessage());
}
catch(IOException v1){
Log.d("error", v1.getMessage());
}
thanks in advance for help
Ok. There are a lot of undefined variables in your story.
First of all, you should try this at a local machine, where you can be sure that this is not a network problem.
Second, try to wrap the receiving code in a endless loop, it will make the debugging easier.
If by now, you found out that your code is actually working on a localhost,
you should check your network configuration on your devices, make sure you are using the right addresses, and both devices are in the same network.
If you have trouble making your code work on a localhost, try to test your server and client independently on a working software, like http://sourceforge.net/projects/sockettest/ for example, it will allow you to make sure that your client and server code is working
Also don't forget about the timing, start your receiver first.
P.S. Please format your code properly.
I've looking into multiple ways to do this and nothing has helped/worked new to Java UDP packets.
My code for Android is started via a service and it runs on a new thread.
Code for waiting:
try {
int port = 58452;
// Create a socket to listen on the port.
DatagramSocket dsocket = new DatagramSocket(port);
// Create a buffer to read datagrams into. If a
// packet is larger than this buffer, the
// excess will simply be discarded!
byte[] buffer = new byte[2048];
// Create a packet to receive data into the buffer
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
// Now loop forever, waiting to receive packets and printing them.
while (true) {
// Wait to receive a datagram
dsocket.receive(packet);
// Convert the contents to a string, and display them
String msg = new String(buffer, 0, packet.getLength());
System.out.println(packet.getAddress().getHostName() + ": "
+ msg);
// Reset the length of the packet before reusing it.
packet.setLength(buffer.length);
}
} catch (Exception e) {
System.err.println(e);
}
Code for sending:
try {
String host = "MY PHONES IP";
int port = 58452; //Random Port
byte[] message = "LAWL,LAWL,LAWL".getBytes();
// Get the internet address of the specified host
InetAddress address = InetAddress.getByName(host);
// Initialize a datagram packet with data and address
DatagramPacket packet = new DatagramPacket(message, message.length,
address, port);
// Create a datagram socket, send the packet through it, close it.
DatagramSocket dsocket = new DatagramSocket();
dsocket.send(packet);
dsocket.close();
System.out.println("Sent");
} catch (Exception e) {
System.err.println(e);
}
}
It sends fine but won't receive on Android. Please help!
Also my Logcat output: http://pastebin.com/Rfw5mSKV
Thanks
-Fusion
http://systembash.com/content/a-simple-java-udp-server-and-udp-client/
I used that to and it works! Thanks to /u/TarkLark or Reddit!
This is my udp_broadcast server code where iam listening on 0.0.0.0
try{
socket = new DatagramSocket (7777,InetAddress.getByName("0.0.0.0"));
socket.setBroadcast(true);
while(true)
{
System.out.println(getClass().getName()+"ready recieve broadcast packets!");
//recieve a packet
byte[] recvBuf = new byte[15000];
DatagramPacket packet = new DatagramPacket(recvBuf,recvBuf.length);
socket.receive(packet);
System.out.println(getClass().getName() +"packet recieved from :" +packet.getAddress().getHostAddress());
System.out.println("data is "+new String(packet.getData()));
String message = new String(packet.getData()).trim();
if(message.equals("p2p_project_node"))
{
byte [] senddata = "I_found_you_did_YOU".getBytes();
DatagramPacket sendpacket= new DatagramPacket(senddata,senddata.length,packet.getAddress(),packet.getPort());
socket.send(sendpacket);
System.out.println("packet sent to "+sendpacket.getAddress().getHostAddress());
}
}
}
on client side iam broadcasting packet 255.255.255.255 so that i get a reply from server
eventually and i endup in getting server ip address
udp_client_side code
try {
c = new DatagramSocket();
c.setBroadcast(true);
byte [] sendData = "p2p_project_node".getBytes();
//this is broadcasting to 255.255.255.255a
try{
DatagramPacket sendPacket = new DatagramPacket(sendData,sendData.length,InetAddress.getByName("255.255.255.255"),7777);
c.send(sendPacket);
System.out.println("rewuest sent to 255.255.255.255");
}
catch(Exception e) {
System.out.println("exception 255.255" +e);
}
on the server side iam getting error saying that
Exception java.net.BindException "Address already in use :cannot bind"
where am i going wrong if someone could help me it would be great Thanks in advance
The address is already in use. You cannot bind your socket to that address. Some other process already has a UDP socket bound to that poet. Possibly a previous instance of your own program.
Don't broadcast to 255.255.255.255. It was deprecated twenty years ago. Use the subnet broadcast address, or better still use multicast.
You can bind your socket to that port, if this port is occupied by a previous instance of your own program. You need to use "reuse" parameter in all instances of your program. Call .setReuseAddress(true); before binding.
Is it possible to either use the same port over multiple socket.send() or specify a port when creating a DatagramSocket? If so how. I am attempting hole-punching and need to listen from the port that is used and I cannot change the port the client is sending from.
try {
DatagramSocket dSocket = new DatagramSocket();
InetAddress serverAddr = InetAddress.getByName(TARGETIP)
int msg_len = currentMsg.length();
byte[] message = currentMsg.getBytes();
DatagramPacket dPacket = new DatagramPacket(message,msg_len,serverAddr,3222);
dSocket.send(dPacket);
updateConversationHandler.post(new systemUIUpdate("UDP Packet from " + dSocket.getLocalPort()));
}
catch (Exception e){
e.getMessage();
e.printStackTrace();
}
Every time this is run via an eventhandler dSocket.getLocalPort() shows a different port.
Yes you can. There are two solutions depending on what you want to do:
If you want to send the packet from a random port but same port everytime, don't close the socket as mentioned in previous answer.
If you even want to choose the port that you which to send from create DatagramSocket as:
DatagramSocket dSocket = new DatagramSocket(CLIENT_PORT);
Of course it does. You're creating a new socket every time, and never closing it, so the port stays in use, so the new socket gets a new port.
If you want the same port, use the same socket.