Tuesday, February 11, 2014

Ask a simple UDP problem.


            
Watched a few simple network communication android tutorial, write your own example of a send data using UDP, very simple stuff, that is the problem, not through the entire code is as follows:

package com.example.udpsend;

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 android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {

@ Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_main);

SendUDP ();
}

private void SendUDP () {
DatagramSocket sendSocket;
DatagramPacket sendPacket;
String data;
InetAddress destIPAddress;
int destPort;
try {
data = "this massage";
destIPAddress = InetAddress.getByName ("127.0.0.1");
destPort = 2345;
sendPacket = new DatagramPacket (data.getBytes (),
data.getBytes (). length, destIPAddress, 22222) ;/ / initialize the data reported
sendSocket = new DatagramSocket ();
sendSocket.send (sendPacket) ;/ / send
sendSocket.close ();
} Catch (SocketException e) {
e.printStackTrace ();
} Catch (UnknownHostException e) {
e.printStackTrace ();
} Catch (IOException e) {
e.printStackTrace ();
}
}

@ Override
public boolean onCreateOptionsMenu (Menu menu) {
/ / Inflate the menu; this adds items to the action bar if it is present
.getMenuInflater () inflate (R.menu.main, menu);.
return true;
}

}

Compiled through, debugging, execution to
sendSocket = new DatagramSocket ();
When it wrong, really do not understand how it is, there used to explain to the next master, thank you.
Reply:
Has been resolved, the problem looks like a privilege.

No comments:

Post a Comment