send data from android to a udp port in web server2008
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 Messag开发者_开发百科e: ");
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.
精彩评论