android UDP通信

转自:http://blog.csdn.net/yearafteryear/article/details/9271763

 源代码:

MainActivity.java

[java]  view plain copy
  1. package com.example.udp;  
  2.   
  3. import java.net.DatagramPacket;  
  4. import java.net.DatagramSocket;  
  5. import java.net.InetAddress;  
  6.   
  7. import android.os.Bundle;  
  8. import android.os.Message;  
  9. import android.app.Activity;  
  10. import android.view.Menu;  
  11. import android.view.View;  
  12. import android.widget.Button;  
  13. import android.widget.EditText;  
  14. import android.widget.TextView;  
  15. import android.os.Handler;  
  16.   
  17. public class MainActivity extends Activity implements  
  18.         android.view.View.OnClickListener {  
  19.     public static final String SERVERIP = "127.0.0.1";   
  20.     public static final int SERVERPORT = 4444;  
  21.     public TextView text1;  
  22.     public EditText input;  
  23.     public Button btn;  
  24.     public boolean start;  
  25.     public Handler Handler;  
  26.   
  27.     @Override  
  28.     protected void onCreate(Bundle savedInstanceState) {  
  29.         super.onCreate(savedInstanceState);  
  30.         setContentView(R.layout.activity_main);  
  31.         text1 = (TextView) findViewById(R.id.textView1);  
  32.         input = (EditText) findViewById(R.id.editText1);  
  33.         btn = (Button) findViewById(R.id.button1);  
  34.         btn.setOnClickListener(this);  
  35.         start = false;  
  36.         new Thread(new Server()).start();  
  37.         try {  
  38.             Thread.sleep(500);  
  39.         } catch (InterruptedException e) {  
  40.   
  41.         }  
  42.         new Thread(new Client()).start();  
  43.         Handler = new Handler() {  
  44.             @Override  
  45.             public void handleMessage(Message msg) {  
  46.                 String text = (String) msg.obj;  
  47.                 text1.append(text);  
  48.             }  
  49.         };  
  50.     }  
  51.   
  52.     public class Client implements Runnable {  
  53.         @Override  
  54.         public void run() {  
  55.             while (start == false) {  
  56.             }  
  57.             try {  
  58.                 Thread.sleep(500);  
  59.             } catch (InterruptedException e1) {  
  60.                 // TODO Auto-generated catch block  
  61.                 e1.printStackTrace();  
  62.             }  
  63.             try {  
  64.                 InetAddress serverAddr = InetAddress.getByName(SERVERIP);  
  65.                 updatetrack("Client: Start connecting\n");  
  66.                 DatagramSocket socket = new DatagramSocket();  
  67.                 byte[] buf;  
  68.                 if (!input.getText().toString().isEmpty()) {  
  69.                     buf = input.getText().toString().getBytes();  
  70.                 } else {  
  71.                     buf = ("Default message").getBytes();  
  72.                 }  
  73.                 DatagramPacket packet = new DatagramPacket(buf, buf.length,  
  74.                         serverAddr, SERVERPORT);  
  75.                 updatetrack("Client: Sending ‘" + new String(buf) + "’\n");  
  76.                 socket.send(packet);  
  77.                 updatetrack("Client: Message sent\n");  
  78.                 updatetrack("Client: Succeed!\n");  
  79.             } catch (Exception e) {  
  80.                 updatetrack("Client: Error!\n");  
  81.             }  
  82.         }  
  83.     }  
  84.   
  85.     public class Server implements Runnable {  
  86.         @Override  
  87.         public void run() {  
  88.             while (start == false) {  
  89.             }  
  90.             try {  
  91.                 InetAddress serverAddr = InetAddress.getByName(SERVERIP);  
  92.                 updatetrack("\nServer: Start connecting\n");  
  93.                 DatagramSocket socket = new DatagramSocket(SERVERPORT,  
  94.                         serverAddr);  
  95.                 byte[] buf = new byte[17];  
  96.                 DatagramPacket packet = new DatagramPacket(buf, buf.length);  
  97.                 updatetrack("Server: Receiving\n");  
  98.                 socket.receive(packet);  
  99.                 updatetrack("Server: Message received: ‘"  
  100.                         + new String(packet.getData()) + "’\n");  
  101.                 updatetrack("Server: Succeed!\n");  
  102.             } catch (Exception e) {  
  103.                 updatetrack("Server: Error!\n");  
  104.             }  
  105.         }  
  106.     }  
  107.   
  108.     public void updatetrack(String s) {  
  109.         Message msg = new Message();  
  110.         String textTochange = s;  
  111.         msg.obj = textTochange;  
  112.         Handler.sendMessage(msg);  
  113.     }  
  114.   
  115.     @Override  
  116.     public boolean onCreateOptionsMenu(Menu menu) {  
  117.         // Inflate the menu; this adds items to the action bar if it is present.  
  118.         getMenuInflater().inflate(R.menu.main, menu);  
  119.         return true;  
  120.     }  
  121.   
  122.     @Override  
  123.     public void onClick(View v) {  
  124.         // TODO Auto-generated method stub  
  125.         if(v.getId()==R.id.button1)  
  126.             start = true;  
  127.     }  
  128. }  
activity_main.xml

[html]  view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>   
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"   
  3.     android:layout_width="fill_parent"   
  4.     android:layout_height="fill_parent"   
  5.     android:orientation="vertical" >  
  6.       
  7. <EditText   
  8.     android:id="@+id/editText1"   
  9.     android:layout_width="match_parent"   
  10.     android:layout_height="wrap_content" >  
  11.     <requestFocus />   
  12. </EditText>  
  13.   
  14. <Button   
  15.     android:id="@+id/button1"   
  16.     android:layout_width="wrap_content"   
  17.     android:layout_height="wrap_content"   
  18.     android:text="Send" />  
  19.   
  20. <TextView   
  21.     android:id="@+id/textView1"   
  22.     android:layout_width="wrap_content"   
  23.     android:layout_height="wrap_content"   
  24.     android:text="Communication History:"   
  25.     android:textAppearance="?android:attr/textAppearanceLarge" />  
  26.   
  27. </LinearLayout>  

AndroidManifest.xml

[html]  view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.example.udp"  
  4.     android:versionCode="1"  
  5.     android:versionName="1.0" >  
  6.   
  7.     <uses-sdk  
  8.         android:minSdkVersion="8"  
  9.         android:targetSdkVersion="16" />  
  10.   
  11.     <uses-permission android:name="android.permission.INTERNET" />  
  12.   
  13.     <application  
  14.         android:allowBackup="true"  
  15.         android:icon="@drawable/ic_launcher"  
  16.         android:label="@string/app_name"  
  17.         android:theme="@style/AppTheme" >  
  18.         <activity  
  19.             android:name="com.example.udp.MainActivity"  
  20.             android:label="@string/app_name" >  
  21.             <intent-filter>  
  22.                 <action android:name="android.intent.action.MAIN" />  
  23.   
  24.                 <category android:name="android.intent.category.LAUNCHER" />  
  25.             </intent-filter>  
  26.         </activity>  
  27.     </application>  
  28.   
  29. </manifest>  


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值