我是剛來的,沒有c幣,求好心人幫忙解答,謝謝謝謝!!!!
package com.example.practice;
import java.net.DatagramSocket;
import java.net.SocketException;
import android.os.Bundle;
import android.app.Activity;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new kaishi().start();
}
class kaishi extends Thread{
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("01");
try {
System.out.println("03");
DatagramSocket socket =new DatagramSocket(50000); //異常,原因 套接字不能被打開
System.out.println("05");
} catch (SocketException e) {
System.out.println("02");
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("04");
}
}
}
··················································································
以上是一個android軟件一個代碼,目的是用UDP協議進行手機之間的通信,代碼內容僅僅就是創建一個DatagramSocket對象。問題是:每次程序進行到創建DatagramSocket對象的時候都會拋出異常,用真機測試輸出結果是:01 03 02 04。這是在Android的工程中寫的,在java工程中就可以成功創建,語法是按照Java的API寫的,但每次都拋出異常,網上說是因為端口號被占用才拋出異常,換了好幾個端口號還是會拋出異常。求可以成功創建DatagramSocket對象的方法.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
System.out.println("01");
try {
System.out.println("03");
new Thread(){
public void run(){
DatagramSocket socket =new DatagramSocket(50000); //異常,原因 套接字不能被打開
}
}.start();
System.out.println("05");
} catch (SocketException e) {
System.out.println("02");
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("04");
}