• Android 简单UDP发送接收


    主代码:

    package com.example.test;
    
    
    
    import java.net.DatagramPacket;
    import java.net.DatagramSocket;
    import java.net.InetAddress;
    
    import android.os.Bundle;
    import android.os.Message;
    import android.app.Activity;
    import android.util.Log;
    import android.view.Menu;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.os.Handler;
    
    public class MainActivity extends Activity implements
              android.view.View.OnClickListener {
         public static final String SERVERIP = "127.0.0.1"; 
         public static final int SERVERPORT = 4444;
         public TextView text1;
         public EditText input;
         public Button btn;
         public Handler Handler;
    
         @Override
         protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
              text1 = (TextView) findViewById(R.id.textView1);
              input = (EditText) findViewById(R.id.editText1);
              btn = (Button) findViewById(R.id.button1);
              btn.setOnClickListener(this);
                        
              Handler = new Handler() {
                   @Override
                   public void handleMessage(Message msg) {
                        String text = (String) msg.obj;
                        text1.append(text);
                   }
              };
              
              
              
              new Thread(new Server()).start();
              new Thread(new Client()).start();
         
         }
    
         public class Client implements Runnable {
              
              private DatagramPacket packet;
              private DatagramSocket socket;
              public Client()
              {
                   
              }
              @Override
              public void run() {
                   while(true)
                   {
                        if(Tools.Queue_Send.size()>0)
                        {
                             Log.d("Client个数", Tools.Queue_Send.size()+"");
                             try {
                                  InetAddress serverAddr = InetAddress.getByName(SERVERIP);
                                  updatetrack("Client: Start connecting
    ");
                                  socket = new DatagramSocket();
                                            
                                  byte[] buf = Tools.Queue_Send.poll().toString().getBytes();
                                                             
                                  packet = new DatagramPacket(buf, buf.length,
                                            serverAddr, SERVERPORT);
                                  updatetrack("Client: Sending ‘" + new String(buf) + "’
    ");
                                  socket.send(packet);
                                  socket.close();
                                  updatetrack("Client: Message sent
    ");
                                  updatetrack("Client: Succeed!
    ");
                             } catch (Exception e) {
                                  updatetrack("Client: Error!
    ");
                             }
                        }
                        
                   }
              }
         }
    
         public class Server implements Runnable {
              @Override
              public void run() {
                   while (true) {
                        try {
                             InetAddress serverAddr = InetAddress.getByName(SERVERIP);
                             updatetrack("
    Server: Start connecting
    ");
                             DatagramSocket socket = new DatagramSocket(SERVERPORT,
                                       serverAddr);
                             byte[] buf = new byte[17];
                             DatagramPacket packet = new DatagramPacket(buf, buf.length);
                             updatetrack("Server: Receiving
    ");
                             socket.receive(packet);
                             updatetrack("Server: Message received: ‘"
                                       + new String(packet.getData()) + "’
    ");
                             updatetrack("Server: Succeed!
    ");
                        } catch (Exception e) {
                             updatetrack("Server: Error!
    ");
                        }
                        
                   }
                   
              }
         }
    
         public void updatetrack(String s) {
              Message msg = new Message();
              String textTochange = s;
              msg.obj = textTochange;
              Handler.sendMessage(msg);
         }
    
         @Override
         public boolean onCreateOptionsMenu(Menu menu) {
              // Inflate the menu; this adds items to the action bar if it is present.
              getMenuInflater().inflate(R.menu.activity_main, menu);
              return true;
         }
    
         @Override
         public void onClick(View v) {
              // TODO Auto-generated method stub
              if(v.getId()==R.id.button1)
              {
                   Tools.Queue_Send.offer(input.getText().toString());
                   Log.d("加入个数", Tools.Queue_Send.size()+"");
              }
                   
                   
         }
    }
    布局代码:
    <? xml version= "1.0" encoding = "utf-8"?>
    < LinearLayout xmlns:android ="http://schemas.android.com/apk/res/android"
        android:layout_width= "fill_parent"
            android:layout_height ="fill_parent"
            android:orientation ="vertical" >
           
    < EditText
            android:id ="@+id/editText1"
            android:layout_width ="match_parent"
            android:layout_height ="wrap_content" >
     
        <requestFocus android:layout_width= "match_parent" />
     
    </ EditText>
     
    < Button
            android:id ="@+id/button1"
            android:layout_width ="wrap_content"
            android:layout_height ="wrap_content"
            android:text = "Send" />
     
    < ScrollView
        android:layout_width= "wrap_content"
        android:layout_height= "wrap_content" >
     
    < TextView
        android:id= "@+id/textView1"
        android:layout_width= "wrap_content"
        android:layout_height= "wrap_content"
        android:scrollbars= "vertical"
        android:text= "Communication History:"
        android:textAppearance= "?android:attr/textAppearanceLarge" />
    </ ScrollView>
    </ LinearLayout>
      Tools类:
    package com.example.test;
    
    import java.util.ArrayList;
    import java.util.LinkedList;
    import java.util.Queue;
    
    public class Tools {
         /**
         * 发送队列
         * */
         public static Queue<String> Queue_Send = new LinkedList<String>(); 
    }
    可以实现发送接收。
    在这之前,我一直想实现点击发送就可以收到。
    我知道服务器端和客户端都是线程一直开着,问题是客户端线程已经开着我怎样才能把要发的数据加载进去。
    开始我想着用Handle类,这样应该可以实现,但做了一下,有点麻烦。
    后面就建了一个静态数据队列,保存要发送的数据,这样就很简单了。
    自己菜可以原谅,如果不学习就不可原谅。
  • 相关阅读:
    [原]将工程由VC6迁移到VS2005
    [原]DirectDraw视频播放要点
    [原]代码优化学习笔记
    [原]Linux文件交换
    [原]计划
    [原]写在2006年的最后一天
    [原]技术发展规划
    FindBugs的安装和使用
    VirtualBox常用命令
    eclipse中统计代码行数
  • 原文地址:https://www.cnblogs.com/owner/p/Android.html
Copyright © 2020-2023  润新知