Android udp port - android

i want to send a udp packet from my laptop to an android device, i write a simple App for that but it doesn't work, i think that the port(5554) that i have been used is the problem.
Code:
`private void runUdpServer()
EditText RecieveText = (EditText) findViewById(R.id.editText1);
EditText check = (EditText) findViewById(R.id.editText2);
String lText;
byte[] lMsg = new byte[MAX_UDP_DATAGRAM_LEN];
DatagramPacket dp = new DatagramPacket(lMsg, lMsg.length);
DatagramSocket ds = null;
RecieveText.setText("try1");
try {
RecieveText.setText("try2");
ds = new DatagramSocket(UDP_SERVER_PORT); // i think the problem is here
//disable timeout for testing
if (ds != null){RecieveText.setText("connected");}
else {RecieveText.setText("not connected");}
RecieveText.setText("try");
ds.receive(dp);
lText = new String(lMsg, 0, dp.getLength());
Log.i("UDP packet received", lText);
RecieveText.setText(lText);
check.setText("port opened");
} catch (SocketException e) {``
check.setText("SocketException");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
check.setText("port didn't open");
} finally {
if (ds != null) {
ds.close();
RecieveText.setText("not connected1");
}
else {RecieveText.setText("not connected1");}
}
check.setText("end");
if (ds != null){RecieveText.setText("connected");}
else {RecieveText.setText("not connected");}
}
}

I dont think it is a port issue... print your error log to have a better idea of faillure.... any way try this ... not checked for any typo.... Also keep in mind that any networking task is better to be inside an async task...
int port =1855; ///any port that you want > 1024
DatagramSocket socket = null;
try {
socket = new DatagramSocket(port);
} catch (SocketException e) {
e.printStackTrace();
}
try {
socket.setBroadcast(true);
} catch (SocketException e) {
e.printStackTrace();
}
//////send socket
int eport = 1616;
InetAddress eip = null;
try {
eip = InetAddress.getByName("192.168.1.1"); ////SERVER IP ADDRESS
} catch (UnknownHostException e) {
e.printStackTrace();
}
DatagramSocket esocket = null;
try {
esocket = new DatagramSocket(eport);
} catch (SocketException e) {
e.printStackTrace();
}
///SENDING
byte[] send= new byte[60*1024];
DatagramPacket send_packet = new DatagramPacket(send, send.length);
try {
socket.send(send_packet);
} catch (IOException e) {
e.printStackTrace();
}
//////Start receive
while(true)
{
byte[] message = new byte[60*1024];
DatagramPacket recv_packet = new DatagramPacket(message, message.length);
try {
socket.receive(recv_packet);
} catch (IOException e) {
e.printStackTrace();
}
///Do something whit recv_packet
}

Related

Send and receive UDP packets to server on different network android

I have looked all over for a solution to this problem, I have not come up with a solution that works.
Currently, I send and receive packets on my android device emulator using my loopback/localHost address. This proccess works successfuly, however when I try running the same code using my computer's public address the server never receives the packets.
private String hostName = "99.248.222.229";
//private String hostName = "10.0.2.2";
private InetAddress hostAddress;
#Override
protected void onCreate(Bundle savedInstanceState)
{
CreateAddress addressGetter = new CreateAddress();
try {
hostAddress = addressGetter.execute(hostName).get();
} catch(Exception e){
e.printStackTrace();
}
Button btnLock = (Button) findViewById(R.id.btnLock);
btnLock.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendReceiveTask = new runUdpClient();
byte[] udpMsg = {(byte)housenumber, (byte)doornumber, LK_MSG, UNLOCK};
System.out.println(hostAddress);
sendPacket = new DatagramPacket(udpMsg, udpMsg.length, hostAddress, portnumber);
DatagramPacket receivePacket = null;
try {
receivePacket = sendReceiveTask.execute(sendPacket).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
currentDoorState = (receivePacket.getData()[3]==UNLOCK);
updateDoorStatus(currentDoorState);
int doorNum = doornumber;
eventArrayList.add(0, (getCurrentTimeStamp() + eventString.replace("doornum", Integer.toString(doorNum)))+ ((currentDoorState) ? "unlocked." : "locked."));
adapter.notifyDataSetChanged();
}
});
}
private class runUdpClient extends AsyncTask<DatagramPacket, Void, DatagramPacket>{
#Override
protected DatagramPacket doInBackground(DatagramPacket ...params){
DatagramSocket ds = null;
//SEND
try {
ds = new DatagramSocket();
DatagramPacket dp;
//dp = new DatagramPacket(udpMsg.getBytes(), udpMsg.length(), hostAddress, portnumber);
dp = params[0];
ds.send(dp);
} catch (SocketException e) {
e.printStackTrace();
}catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
//RECEIVE
DatagramPacket incomingPacket = new DatagramPacket(new byte[100], 100);
try {
ds.setSoTimeout(1000);
} catch (SocketException e) {
e.printStackTrace();
}
try {
ds.receive(incomingPacket);
} catch (IOException e){
e.printStackTrace();
}finally{
if(ds != null) ds.close();
}
System.out.println("Packet recieved from server" + Arrays.toString(incomingPacket.getData()));
return incomingPacket;
}
}

Udp not receiving data from server (android client, pc java server)

i am making a chat application for android using UDP.
Everything works fine in lan devices, I can send and receive messages from client and from server.
When i connect to an other network with my android, i can send messages, the server receives them but the response is never received on android.
Client Receive code
Runnable periodicTask = new Runnable() {
public void run() {
// Invoke method(s) to do the work
System.out.println("Waiting for data");
byte[] receiveData = new byte[2028];
byte[] sendData = new byte[2028];
boolean portTaken=false;
DatagramSocket serverSocket=null;
ServerSocket socket = null;
try {
socket = new ServerSocket(6667);
} catch (IOException e) {
System.out.println("ERRORRRRRRRRRRRRRR");
} finally {
if (socket != null)
try {
socket.close();
serverSocket= new DatagramSocket(6667);
} catch (IOException e) { e.printStackTrace(); }
}
DatagramPacket receivePacket = new DatagramPacket(receiveData,receiveData.length);
try {
serverSocket.receive(receivePacket);
System.out.println("GOT THEM!");
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayInputStream in = new ByteArrayInputStream(receiveData);
ObjectInputStream is = null;
try {
is = new ObjectInputStream(in);
} catch (IOException e) {
e.printStackTrace();
}
Data student = null;
try {
student = (Data) is.readObject();
l.add(student.toString());
mHandler.sendEmptyMessage(0);
System.out.println(student);
serverSocket.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
};
Server Send Code
for (DatagramPacket packet:clients){
if (!packet.getAddress().equals(receivePacket.getAddress())){
System.out.println("current ip address " + receivePacket.getAddress());
System.out.println("Sending to " + packet.getAddress());
DatagramSocket s = new DatagramSocket();
InetAddress local =packet.getAddress();//editTextAddress.getText().toString());//InetAddress.getByName("192.168.1.74");
System.out.println(local.toString());
//int msg_length =student.//sentence.length();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(outputStream);
os.writeObject(student);
byte[] data2 = outputStream.toByteArray();
int msg_length =data2.length;
DatagramPacket p = new DatagramPacket(data2, msg_length, local,
6667);
s.send(p);
s.close();
}
What might be the case ?
Thank you for your time

Android get data from pc using socket

Android send data to pc - client side (work with success):
Button send = (Button) findViewById(R.id.sendSocket);
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
Socket socket = new Socket("IP",8000);
DataOutputStream DOS = new DataOutputStream(socket.getOutputStream());
DOS.writeUTF("Hello");
socket.close();
}catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Now How can i keep listening to receive data from pc (server side) ???
that's what i am tryng (not working) :
try {
Boolean end = false;
ServerSocket ss = new ServerSocket(8000);
while(!end){
//Server is waiting for client here, if needed
Socket s = ss.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter output = new PrintWriter(s.getOutputStream(),true); //Autoflush
String st = input.readLine();
recive.setText(st);
s.close();
//if ( STOPPING conditions){ end = true; }
}
ss.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
recive.setText(e.toString());
}
try something like this :
ServerSocket ss = new ServerSocket(8000);
Socket s = ss.accept();
BufferedReader input = new BufferedReader (new InputStreamReader (s.getInputStream ()));
while (true)
{
String st = "";
try
{
st = input.readLine ();
System.out.println (st);
}
catch (IOException e)
{
//error ("System: " + "Connection to server lost!");
System.exit (1);
break;
}
}
ss.close();

Android Socket: Send Data Repeatedly with a Fixed Time Interval

I have a code that sends data on click. However, I want to send data repeatedly with a fixed time interval.
public void onClick(View view) {
try {
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(str);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
any help would be appreciated.
Create a new thread with a while loop and a Thread.sleep() call.
This post has all the code you need:
How to run a Runnable thread in Android?

Android socket connect freezing

I am trying to implement a simple socket that sends and receives strings from a server.
The following code is freezing the application, not sure if I have done something obviously wrong?
public String internetRoutesRetrieve(String userName) {
String command = null;
String response = null;
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket("Hidden IP", HiddenPort);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
command = "SEARCH <" + userName + ">";
dataOutputStream.writeUTF(command);
response = dataInputStream.readUTF();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response;
}
Thanks
Edit: It seems the program is freezing when I am trying to save the response from the server
see AsyncTask for proper client server communication on Android application.
you'd usualy get android.os.NetworkOnMainThreadException if you don't but I'd give it a try.

Categories

Resources