safedispatch-mobile/safeDispatch/src/main/java/com/safemobile/lib/sound/UDPclient.java
2022-03-14 11:53:00 +02:00

110 lines
2.8 KiB
Java

package com.safemobile.lib.sound;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.safemobile.lib.SM;
public class UDPclient implements Runnable{
public String serverHostname = new String ("10.120.1.114");//
private int UDP_SERVER_PORT_IN = 50002;
private int UDP_SERVER_PORT_OUT = 50001;
private DatagramSocket ds = null;
private Thread listenThread;
private InetAddress serverAddr=null;
private DatagramPacket dp_send = null;
private DatagramPacket dp_recv = null;
byte[] buffer = new byte[4096];
public Boolean isAlive = false;
private List<IUDPListener> _listeners = new ArrayList<IUDPListener>();
public UDPclient(String ip)
{
SM.Debug("---UDPclient construcort---IP:"+ip);
serverHostname = ip;
try {
serverAddr = InetAddress.getByName(serverHostname);
ds = new DatagramSocket(UDP_SERVER_PORT_IN);
dp_recv = new DatagramPacket(buffer, buffer.length);
isAlive = true;
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
listenThread = new Thread(this, "UDPclient");
listenThread.start(); // (2) Start the thread.
Send(new byte[]{1}, 1);
SM.Debug("=====UDPclient construcort ===END====");
}
@Override
public void run() {
while(isAlive)
{
try
{
ds.receive(dp_recv);
//String msg = new String(buffer, 0, dp_recv.getLength());
//SM.Debug("UDPclient recv b:"+dp_recv.getLength());
_fireDataArrived(buffer,dp_recv.getLength());
}
catch (IOException e) {
SM.Debug("break:"+e.toString());
}
/*
try {
Thread.sleep(1);
} catch (InterruptedException e) {
SM.Debug("break:"+e.toString());
}
*/
}
}
public Boolean Send(byte[] data,int len)
{
Boolean ret = true;
try
{
dp_send = new DatagramPacket(data, len, serverAddr, UDP_SERVER_PORT_OUT);
ds.send(dp_send);
}
catch (IOException e) {
SM.Debug("break:"+e.toString());
ret = false;
}
return ret;
}
public synchronized void addUDPListener( IUDPListener l ) {
_listeners.add( l );
}
public synchronized void removeUDPListener( IUDPListener l ) {
_listeners.remove( l );
}
private synchronized void _fireDataArrived(byte[] data, int len) {
UDPevent event = new UDPevent( this, data, len );
Iterator<IUDPListener> listeners = _listeners.iterator();
while( listeners.hasNext() ) {
( (IUDPListener) listeners.next() ).dataRecv(event);
}
}
}