Hi I am currently making a project in Android using DatagramSockets and I'm not really that good in programming. I am making a registration page. My android device connects to the pc with information like username and receiptcode. My pc can receive the data. When my pc receives the data I need to check if the receiptcode is valid and unused. Then I would send to the client if it is invalid, unused, used or valid. The problem is my android device can't receive the data the pc sent. I really need your help guys. Currently I'm using an emulator. I need experts help. Here is my code:
Android Device:
public class RegisterAsyncTask extends AsyncTask<String, Integer, String>{
private DatagramSocket socket;
private DatagramPacket p;
private byte[] receiveData = new byte[1024];
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
InetAddress local = InetAddress.getByName("10.0.2.2");
socket = new DatagramSocket();
p = new DatagramPacket(params[0].getBytes(), params[0].length(),local,12345);
socket.send(p);
Log.d ("asd", "Packet sent");
p = new DatagramPacket (receiveData, receiveData.length);
Log.d ("asd", "Receiving packet");
socket.receive(p);
Log.d ("asd", "Packet received");
String message = new String (p.getData(), 0 , p.getLength());
Log.d ("asd", message);
return message;
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
PC:
public class HandleAClient {
private DatagramSocket socket;
private DatagramPacket packet;
private int server_port = 12345;
private byte[] receiveData = new byte[1024];
private String receiptCode;
private InetAddress clientAddress;
private String errorMessage;
public HandleAClient (DatagramSocket socket, DatagramPacket packet) {
//Initializes instance variables
this.socket = socket;
this.packet = packet;
}
public void registerClient () {
try {
String message = new String (packet.getData(),0,packet.getLength());
Parser parser = new Parser();
receiptCode = parser.getReceiptCode(message);
System.out.println (receiptCode);
System.out.println ("Message: " + message + " on " + packet.getAddress() + " on port " + server_port);
String cadd = packet.getAddress().toString();
String newcadd = cadd.substring(1, cadd.length());
System.out.println (newcadd);
clientAddress = InetAddress.getByName(newcadd);
if (!ControlVariables.db.checkReceiptCode(receiptCode)) {
errorMessage = "Invalid Code";
System.out.println (errorMessage);
packet = new DatagramPacket(errorMessage.getBytes(), errorMessage.length(),clientAddress,12345);
socket.send(packet);
System.out.println ("error message send" + " to " +newcadd);
}
else {
ReceiptCode rc = new ReceiptCode();
rc = ControlVariables.db.getReceiptCode(receiptCode);
if (rc.getStatus().equals("used")) {
errorMessage = "Used Code";
packet = new DatagramPacket(errorMessage.getBytes(), errorMessage.length(),clientAddress,12345);
socket.send(packet);
}
else {
System.out.println (receiptCode);
System.out.println ("Message: " + message + " on " + packet.getAddress() + " on port " + server_port);
errorMessage = "Successful";
packet = new DatagramPacket(errorMessage.getBytes(), errorMessage.length(),clientAddress,12345);
socket.send(packet);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
Since I can't add a comment to your post, I'll try this way.
I've read that emulator can't use real internet connection. So I do not realize how you send data to PC.
Please provide more information on errors or info you have about not receiving packets.
Related
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.
I want to make my android app open socket to my windows console app and they communicate with each other. The socket is opened and data is sent and received in windows app, but my android app does not receive the answer which sent by windows. I watch the packets in my android and I saw the packets are coming but I do not know why my app do not receive it!
windows app server class:
class Server
{
private TcpListener tcpListener;
private Thread listenThread;
public Server()
{
Console.WriteLine("\nStarting server...");
this.tcpListener = new TcpListener(IPAddress.Any, 1234);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
}
private void ListenForClients()
{
Console.WriteLine("\nWaiting for clients to connect...");
this.tcpListener.Start();
while (true)
{
//blocks until a client has connected to the server
TcpClient client = this.tcpListener.AcceptTcpClient();
//create a thread to handle communication with connected client
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
}
private void HandleClientComm(object client)
{
Console.WriteLine("\nIncoming from client...");
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
try
{
while (true)
{
bytesRead = 0;
try
{
//blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);
}
catch
{
//a socket error has occured
break;
}
if (bytesRead == 0)
{
//the client has disconnected from the server
break;
}
//message has successfully been received
ASCIIEncoding encoder = new ASCIIEncoding();
Console.WriteLine("\nReceived: \n\n" + encoder.GetString(message, 0, bytesRead));
//By FMR
string response = "random responsive: " + new Random().Next(1000).ToString() + "\n";//"\r\n";
//writeData(clientStream, response);
byte[] msg = System.Text.Encoding.ASCII.GetBytes(response);
// Send back a response.
clientStream.Write(msg, 0, msg.Length);
clientStream.Flush();
Console.WriteLine("\nResponed ..." + response);
}
}
catch (Exception ex)
{
Console.WriteLine("\nException while: " + ex.Message);
}
tcpClient.Close();
}
}
my android thread:
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
Socket socket = null;
ServerSocket serverSocket = null;
Boolean bRun = true;
try {
socket = new Socket(ip, port);
if(outputStream == null) {
outputStream = new DataOutputStream(socket.getOutputStream());
}
// become server
serverSocket = new ServerSocket(port);
Log.i(G.TAG, "before serverSocket.accept");
socket = serverSocket.accept();
Log.i(G.TAG, "response recieve: ");
inputStream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
catch (Exception e) {
try {
serverSocket.close();
} catch (IOException e1) {
Log.e(G.TAG, "serverSocket.close() e: " + e1.getMessage());
}
try {
socket.close();
} catch (IOException e1) {
Log.e(G.TAG, "socket.close() e: " + e1.getMessage());
}
}
Log.i(G.TAG, "after start recieve: ");
while (bRun) {
try {
Log.i(G.TAG, "while start: ");
String message = inputStream.readLine();
Log.i(G.TAG, "response message: " + message);
if (message != null) {
setListMessage(false, message);
}
}
catch (IOException e) {
bRun = false;
Log.e(G.TAG, "while bRun e: " + e.getMessage());
}
}
}
});
thread.start();
// in another function, my message is sent successfully from android and receive in windows
I found the problem, this line
socket = serverSocket.accept();
made the problem when I comment the line, the android app received the response!
Does anybody know why?
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 want to send data(latitude and longitude )to a web server (windows server 2008) who"s ip and udp port is known from my android application .how to do so ?
here is a sample code which i m trying but data is not received to other end
public class UDPServer extends Activity {
WebView view;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState) ;
setContentView(R.layout.main);
view=(WebView) findViewById(R.id.webView1);
try {
String serverHostname = new String ("ip and udp port");
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName(serverHostname);
System.out.println ("Attemping to connect to " + IPAddress +
") via UDP port 7777");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
System.out.print("Enter Message: ");
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
Log.i("send","send");
System.out.println ("Sending data to " + sendData.length +
" bytes to server.");
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress,7777);
clientSocket.send(sendPacket);
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
System.out.println ("Waiting for return packet");
clientSocket.setSoTimeout(10000);
try {
clientSocket.receive(receivePacket);
String modifiedSentence =
new String(receivePacket.getData());
InetAddress returnIPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
System.out.println ("From server at: " + returnIPAddress +
":" + port);
System.out.println("Message: " + modifiedSentence);
}
catch (SocketTimeoutException ste)
{
System.out.println ("Timeout Occurred: Packet assumed lost");
}
clientSocket.close();
}
catch (UnknownHostException ex) {
System.err.println(ex);
}
catch (IOException ex) {
System.err.println(ex);
}
}
In UDP, unlike TCP, there is no connection established. Every UDP packet travels on it's own.
My guess is that you can send a UDP packet to server, but you do not receive the return packet. The reason for this is NAT which is used on all home routers and cellular networks. NAT prevents delivery of inbound (internet to device) packets.
To test this assumption, try this with device and server on the same local network.
I have a TCP Client in Android (Java program in Eclipse). The server was another Java app running in Eclipse. Everything works fine in this situation.
When I tried to receive message from my colleague's app (developed in Rhapsody and I think C++), I receive the message only after his app is closed and not while his app is running and sending messages. Do you have any idea why this happens?
Thank you for the time and effort on this.
Cheers,
Madhu
The java server is like this:
public class TCPSendServer implements Runnable{
public static final String SERVERIP = "192.168.178.24";
public static final int SERVERPORT = 1200;
//static Category cat = Category.getInstance(TCPSendServer.class.getName());
//cat.debug("Start of main()");
public void run() {
try {
System.out.println("S: Connecting...");
ServerSocket serverSocket = new ServerSocket(SERVERPORT);
String msg = "<MSG><N>shiftDirection</N><V>1</V></MSG>";
String msg1 = "<MSG><N>vehicleSpeed</N><V>120</V></MSG>";
String msg2 = "SD<!N><V>0<!V><!MSG>";
//while (true) {
Socket client = serverSocket.accept();
try {
System.out.println("S: Sending: '" + msg + "'");
PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(client.getOutputStream())),true);
Thread.sleep (5000);
out.println(msg);
Thread.sleep (5000);
//out.println(msg2);
Thread.sleep (5000);
out.println(msg1);
//out.flush();
System.out.println("S: Sent.");
System.out.println("S: Done.");
} catch(Exception e) {
System.out.println("S: Error");
e.printStackTrace();
} //finally {
// client.close();
//}
//}
} catch (Exception e) {
System.out.println("S: First try error");
e.printStackTrace();
}
}
public static void main (String a[]) {
Thread desktopServerThread = new Thread(new TCPSendServer());
desktopServerThread.start();
}
}
The Android client code:
Main activity:
public class TCPListen extends Activity implements TCPListener {
private TextView mTitle;
public String data[] = new String[2];
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
// Set up the window layout
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.main);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
// Set up the custom title
mTitle = (TextView) findViewById(R.id.title_left_text);
mTitle.setText(R.string.app_name);
mTitle = (TextView) findViewById(R.id.title_right_text);
//TcpServiceHandler handler=new TcpServiceHandler(this);
//handler.execute("192.168.178.24");
TcpServiceHandler handler = new TcpServiceHandler(this,this);
Thread th = new Thread(handler);
th.start();
}
public String[] callCompleted(String source){
Log.d("TCP", "Std parser " + source);
mTitle.setText(source);
//String data[] = new String[2];
//if (source.matches("<MSG><N>.*</N><V>.*</V></MSG>")) {
Document doc = null;
try{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = (Document) db.parse(new ByteArrayInputStream(source.getBytes()));
NodeList n = doc.getElementsByTagName("N");
Node nd = n.item(0);
String msgName = nd.getFirstChild().getNodeValue();
NodeList n1 = doc.getElementsByTagName("V");
Node nd1 = n1.item(0);
String tmpVal = nd1.getFirstChild().getNodeValue();
data[0] = msgName;
data[1] = tmpVal;
Log.d("TCP", "Inside Std parser " + data[0] + " " + data[1]);
//actionOnData(data[0], data[1]);
}
catch(Exception e){
e.printStackTrace();
}
Log.d("TCP", "Just outside Std parser " + data[0] + " " + data[1]);
return data;
//} else Log.d("TCP", "Message in wrong format " + source);
//mTitle.setText("Message in wrong format " + source);
//return data;
}
Interface:
public interface TCPListener {
public String[] callCompleted(String msg);
}
TCPServiceHandler:
public class TcpServiceHandler implements Runnable {
TCPListener _listener;
private Activity _act;
public TcpServiceHandler(TCPListener listener, Activity act){
_listener = listener;
_act = act;
}
public synchronized void run() {
// TODO Auto-generated method stub
//if(socket==null){
try {
InetAddress serverAddr = InetAddress.getByName("192.168.178.25");
Socket socket = new Socket(serverAddr, 1200);
//
while(true){
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
final String str = in.readLine();
this._act.runOnUiThread(new Runnable(){
public void run() {
_listener.callCompleted(str);
}
});
}
catch(Exception e){
e.printStackTrace();
}
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
This is problem with the SERVERIP here. Are you running your app from an emulator in your local machine? Your emulator is not part of your LAN. Emulator runs behind a virtual router/firewall service that isolates it from your development machine's network interfaces and settings and from the internet.
So you need to use network redirections or port forwarding to achieve communication with the server which is on a separate machine.
If you are running the app on a device then you can make that device as part of your network and then it should work.
There has been a solution, at least for the time being. I use readLine() to read contents of sockets and this expects \n or \r or similar characters until it returns the contents. This was not the issue for me when both server and client were in Java. But when the client had to receive messages from a different app, I faced this problem. It was overcome by just adding \n to the end of message sent by the other app.