Send and receive UDP packets to server on different network android - 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;
}
}

Related

Chat along with another data sending in socket programming android

I'm developing a project where client sends screenshots of its activity to server where the bitmap is converted to string.For me it works well.I would like to add a chat between client and server in this project.How can I achieve this?Any kind of help is accepted.
Client Code
public class Client2 extends AsyncTask<Void, Void, Void> {
public static String dstAddress;
int dstPort;
String response= new String() ;
String msg_server=new String();
Context context;
public static ArrayList<Bitmap>ss=new ArrayList<>();
public static Socket socket;
Client2(Context ic,String addr, int port,String msg) {
context=ic;
dstAddress = addr;
dstPort = port;
msg_server=msg;
}
#Override
protected Void doInBackground(Void... arg0) {
socket = null;
ObjectOutputStream dataOutputStream = null;
ObjectInputStream dataInputStream = null;
try {
socket = new Socket(dstAddress, dstPort);
dataOutputStream = new ObjectOutputStream(
socket.getOutputStream());
dataInputStream = new ObjectInputStream(socket.getInputStream());
if(msg_server != null){
dataOutputStream.writeObject(msg_server);
dataOutputStream.flush();
}
response = (String) dataInputStream.readObject();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try { socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Toast.makeText(context, response, Toast.LENGTH_SHORT).show();
}}
Server Code
public class Server extends Thread{
ServerSocket serverSocket;
Viewer activity;
static final int SocketServerPORT = 8080;
int count = 0;
int sc=0;
Bitmap bmviewer;
String msgtoclient,msgfromclient;
ArrayList<Bitmap>ser=new ArrayList<>();
public Server(Activity context,String msg )
{
activity= (Viewer) context;
msgtoclient=msg;
}
#Override
public void run() {
Socket socket = null;
ObjectInputStream dataInputStream = null;
ObjectOutputStream dataOutputStream = null;
try {
// serverSocket = new ServerSocket(SocketServerPORT);
serverSocket = new ServerSocket(); // <-- create an unbound socket first
serverSocket.setReuseAddress(true);
serverSocket.bind(new InetSocketAddress(SocketServerPORT));// serverSocket.setReuseAddress(true);
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Viewer.demo.setText("Port No: "
+ serverSocket.getLocalPort());
}
});
while (true) {
socket = serverSocket.accept();
dataInputStream = new ObjectInputStream(
socket.getInputStream());
dataOutputStream = new ObjectOutputStream(
socket.getOutputStream());
String messageFromClient = new String();
//If no message sent from client, this code will block the program
messageFromClient = (String) dataInputStream.readObject();
count++;
bmviewer = (stringtobitmap(messageFromClient));
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
//Viewer.demo.setText(message);
sc++;
saveimage(bmviewer, sc);
// Viewer.images.setImageBitmap(bmviewer);
Viewer.imageGallery.addView(getImageView(bmviewer));
}
});
if (msgtoclient.equals("")){
String reply="received";
dataOutputStream.writeObject(reply);
dataOutputStream.flush();}
else {
dataOutputStream.writeObject(msgtoclient);
dataOutputStream.flush();
}
}
}catch(EOFException e){
e.printStackTrace();
final String errMsg = e.toString();
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Snackbar snackbar=Snackbar.make(Viewer.relativeLayout,errMsg,Snackbar.LENGTH_LONG);
snackbar.show();
}
});
} catch(IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
final String errMsg = e.toString();
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Snackbar snackbar=Snackbar.make(Viewer.relativeLayout,errMsg,Snackbar.LENGTH_LONG);
snackbar.show();
}
});
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
private View getImageView(Bitmap image) {
ImageView imageView = new ImageView(activity);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(0, 0, 10, 0);
imageView.setLayoutParams(lp);
imageView.setImageBitmap(image);
return imageView;
}
private void saveimage(Bitmap bmp,int c) {
sc=c;
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/screenshare_viewer");
myDir.mkdirs();
//Random generator = new Random();
// int n = 10000;
// n = generator.nextInt(n);
String fname = "Image-"+sc +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private Bitmap stringtobitmap(String message) {
try{
byte [] encodeByte= Base64.decode(message,Base64.DEFAULT);
Bitmap bitmap= BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
return bitmap;
}
catch(Exception e){
e.getMessage();
return null;
}
}
}

transfer udp packets in android

These codes are for sending and receiving udp packets in android. When I run it in emulator, It can receive data. But it isn't work in real devices. what is problem?
In Eclipse:
public class UdpServer extends Activity {
/** Called when the activity is first created. */
private TextView textView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView = (TextView) findViewById(R.id.text1);
runUdpServer();
}
private static final int UDP_SERVER_PORT = 11111;
private static final int MAX_UDP_DATAGRAM_LEN = 1500;
private void runUdpServer() {
String lText;
byte[] lMsg = new byte[MAX_UDP_DATAGRAM_LEN];
DatagramPacket dp = new DatagramPacket(lMsg, lMsg.length);
DatagramSocket ds = null;
try {
ds = new DatagramSocket(UDP_SERVER_PORT);
//disable timeout for testing
//ds.setSoTimeout(100000);
ds.receive(dp);
lText = new String(lMsg, 0, dp.getLength());
Log.i("UDP packet received", lText);
textView.setText(lText);
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ds != null) {
ds.close();
}
}
}
}
UdpClient.java:
public class UdpClient extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
runUdpClient();
finish();
}
private static final int UDP_SERVER_PORT = 11111;
private void runUdpClient() {
String udpMsg = "hello world from UDP client " + UDP_SERVER_PORT;
DatagramSocket ds = null;
try {
ds = new DatagramSocket();
InetAddress serverAddr = InetAddress.getByName("127.0.0.1");
DatagramPacket dp;
dp = new DatagramPacket(udpMsg.getBytes(), udpMsg.length(), serverAddr, UDP_SERVER_PORT);
ds.send(dp);
} catch (SocketException e) {
e.printStackTrace();
}catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ds != null) {
ds.close();
}
}
}
}
Manifest:
<uses-permission android:name="android.permission.INTERNET"/>
This is code link.
Link
Does it need a modem? Does it need connecting to the internet? Does it need Wi-Fi on?

Datagram socket android

Hi guys i'm trying to make an app that connect to my arduino device using a datagramsocket. When i launch the app it should write in my edittext ip address of my arduino but it doesn't appear. I think the problem is that the UdcClientServer class is launched only one time at startup but it should be executed in realtime.
Here the main activity code:
public class MainActivity extends Activity {
private EditText textIpScheda=null;
private EditText textUdpPort=null;
private UdpClientServer cu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textIpScheda = (EditText) findViewById(R.id.textIpScheda);
textUdpPort = (EditText) findViewById(R.id.textUdpPort);
try {
cu = new UdpClientServer(this);
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public EditText getTextIpScheda(){
return textIpScheda;
}
public EditText getTextUdpPort() {
return textUdpPort;
}
}
Here the UdpClientServer class:
public class UdpClientServer {
public static String sReceive;
private static DatagramSocket dSocket;
private Socket socket;
private String stringa;
int receiveBufferSize = 1024;
int portUdp = 0;
final String PINGACMD = "AT*PINGA001";
InetAddress ipScheda;
byte[] receiveData = new byte[receiveBufferSize];
private MainActivity gui;
public UdpClientServer(MainActivity gui) throws SocketException, IOException {
this.gui = gui;
portUdp = 5200;
dSocket = new DatagramSocket(portUdp);
}
public void run(){
while (true) {
Arrays.fill(receiveData, (byte) 0);
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
try {
dSocket.receive(receivePacket);
} catch (IOException e) {
e.printStackTrace();
}
ipScheda = receivePacket.getAddress();
int port = receivePacket.getPort();
gui.getTextUdpPort().setText("" + port);
gui.getTextIpScheda().setText(ipScheda.getHostAddress());
sReceive = new String(receivePacket.getData());
this.sendCommand(PINGACMD);
}
}
public void sendCommand(String outSentence){
byte[] sendData = outSentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ipScheda, portUdp);
try {
dSocket.send(sendPacket);
Thread.sleep(100);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
finally {
}
}
}
thanks everybody

closing client let the server crash

I've a simple client and server on android. Everything works fine except when I close the client app then the server stops working the app closes.
I think it's about not closing the socket. But when I close the socket in the client the server still stops working.
I'm running a thread on the server. This is my server code:
this.serverThread = new Thread(new ServerThread());
this.serverThread.start();
}
#Override
protected void onStop() {
super.onStop();
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class ServerThread implements Runnable {
public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(SERVERPORT);
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
try {
socket = serverSocket.accept();
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class CommunicationThread implements Runnable {
private Socket clientSocket;
private BufferedReader input;
public CommunicationThread(Socket clientSocket) {
this.clientSocket = clientSocket;
try {
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
String read = input.readLine();
updateConversationHandler.post(new updateUIThread(read));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class updateUIThread implements Runnable {
private String msg;
private boolean feedback = false;
public updateUIThread(String str) {
msg = str;
}
#Override
public void run() {
parseCommand();
if(feedback)
{
textFeedback.setText(msg);
feedback = false;
}
else
{
textTv.setText(msg);
}
}
if(msg != null)
parseCommand();
and in
while (!Thread.currentThread().isInterrupted()) {
try {
String read = input.readLine();
if(read == null)
{
clientSocket.close();
Log.d("Test","SOCKET CLOSED");
return;
}
updateConversationHandler.post(new updateUIThread(read));
} catch (IOException e) {
e.printStackTrace();
}
}

Android udp port

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
}

Categories

Resources