2012-07-18 111 views
0

我將數據從PC發送到Android。但我無法在Android中使用UDP接收數據。如何在Android中使用UDP接收數據?我如何在android-display上看到收到的數據?誰能幫我?如何在Android中接收UDP數據?

代碼是在這裏:

public class MainActivity extends Activity { 
    EditText textOut; 
    EditText port; 
    int UDP_SERVER_PORT = 8255; 
    public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    // setContentView(R.layout.main); 
    try { 
     int port = UDP_SERVER_PORT; 
     Log.d("UDP", "Connecting.."); 
     DatagramSocket clientsocket = new DatagramSocket(port); 
     byte[] receivebuf = new byte[1024]; 
     DatagramPacket receivepacket = 
     new DatagramPacket(receivebuf,receivebuf.length); 
     clientsocket.receive(receivepacket); 
     String modifiedSentence = new String(receivepacket.getData()); 
     System.out.println("FROM SERVER:" + modifiedSentence); 
     clientsocket.close(); 
    } catch (Exception e) { 
     Log.e("UDP", "C: Error", e); 
    } 
    }; 
} 

回答

0

對於希望數據recevied讓我們假設數據轉換爲字符串,然後你需要一個視圖,設置其值等於數據recevied。這對你有意義嗎?

+0

謝謝。我怎樣才能做到這一點? – 2012-07-18 09:38:29

+0

其簡單初始化如下所示的TextView TextView viewToShow = new TextView(context); viewtoShow.settext(//從socket接收到的字符串); – Shachillies 2012-07-18 09:51:21

+0

String receivingtring = new String(receivepacket.getData()); textview.setText(「Received String」+ receivingtring); – 2012-07-18 10:07:39