我试图让我的测试应用程序通过 UDP 套接字发送字符串。它不断在线抛出AndroidRuntime
错误soc.send(pac);
。我已经在android_manifest
文件中设置了所需的权限。
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
private EditText editText1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = (Button) findViewById(R.id.button1);
editText1 = (EditText) findViewById(R.id.editText1);
button1.setOnClickListener(new View.OnClickListener() {
String text= editText1.toString();
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
udpmsg(text);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public void udpmsg(String text) throws java.io.IOException
{
InetAddress to = InetAddress.getByName("192.168.0.105");
int port=55505;
DatagramSocket soc = new DatagramSocket();
byte[] data = text.getBytes();
DatagramPacket pac = new DatagramPacket(data, data.length, to, port);
soc.send(pac);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}