zoukankan      html  css  js  c++  java
  • 安卓UDP通信2

    服务器实现一发一收

    服务器代码:

    import java.net.*;
    import java.io.*;
    
    public class udpRecv2
    {
        /*
        * 创建UDP传输的接收端
        * 1.建立udp socket服务,因为是要接收数据,必须指明端口号
        * 2,创建数据包,用于存储接收到的数据。方便用数据包对象的方法处理数据
        * 3,使用socket服务的receive方法将接收的数据存储到数据包中
        * 4,通过数据包的方法解析数据包中的数据
        * 5,关闭资源
    
        *抛一个大异常:IOException
        */
        public static void main(String[] args) throws IOException{
            //1,创建udp socket服务
            DatagramSocket ds = new DatagramSocket(10000);
    
            //2,创建数据包
            byte[] buf =new byte[1024];
            DatagramPacket dp =new DatagramPacket(buf,buf.length);
    
            //3,使用接收的方法将数据包存储到数据包中
            ds.receive(dp);//阻塞式
    
            //4.通过数据包对象的方法,解析其中的数据
            String ip = dp.getAddress().getHostAddress();
            int port  = dp.getPort();
            String content = new String(dp.getData(),0,dp.getLength());
            System.out.println(ip+"::" +port+":"+content);
            /*回发给手机数据*/
            //首先获取端口和地址
            InetAddress addr = dp.getAddress();
            String sendStr = "Hello ! 我是服务器";
            byte[] sendBuf;
            sendBuf = sendStr.getBytes("utf-8");//必须转换utf8,否则安卓显示乱码
            DatagramPacket sendPacket 
                = new DatagramPacket(sendBuf , sendBuf.length , addr , port );
    
            ds.send(sendPacket);
            //5关闭资源
            ds.close();
    
            
            
        }
    }
    udpRecv2.java

    安卓客户端代码:

    后台:

    package com.simpleclientudp;
    
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.net.DatagramPacket;
    import java.net.DatagramSocket;
    import java.net.InetAddress;
    import java.net.Socket;
    import java.net.UnknownHostException;
    
    
    
    
    
    import android.app.Activity;
    import android.os.Bundle;
    
    import android.util.Log;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    
    
    public class MainActivity extends Activity {
        
         private EditText mEditText = null;  
         private TextView mTextView = null;  
         private Button mButton = null;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            mButton = (Button)findViewById(R.id.mButton);  
            mEditText = (EditText)findViewById(R.id.mEditText);  
            mTextView = (TextView)findViewById(R.id.mTextView); 
            mButton.setOnClickListener(new StartSocketListener());
        }
        //启动按钮监听
        class StartSocketListener implements OnClickListener{
              @Override
              public void onClick(View v) {
                new ServerThread().start();
              } 
            }
           
        
       
        class ServerThread extends Thread{
            // UDP协议
            @Override
            public void run()
            {    DatagramSocket ds=null;
                try
                {
                    //1.udpsocket服务对象,使用DatagramSocket创建,可以指明本地IP和端口
                    //当然也可以不指明,已测试成功
                    //现在仅仅指明手机端口为8888
                     ds = new DatagramSocket(8888);
    
                    //2.获取文本框数据,将要发送的数据封装到数据包中
                 // 把用户输入的内容发送给server  
                    String str= mEditText.getText().toString(); 
                    byte[] buf =str.getBytes("gbk");
                    DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.108"),10000);
    
                    //3.udp发送,使用socket服务将数据包发送出去
                    ds.send(dp);
                    /*接收数据*/
                    byte[] recvBuf = new byte[1024];
                    DatagramPacket recvPacket
                        = new DatagramPacket(recvBuf , recvBuf.length);
                    ds.receive(recvPacket);
                    String recvStr = new String(recvPacket.getData() , 0 ,recvPacket.getLength());
                    mTextView.setText("收到udp服务器: 	" + recvStr);
                    //4.关闭连接
                    //ds.close();
                }
                catch(UnknownHostException e) {  
                    Log.e("UDP errror", "192.168.1.108 is unkown server!");  
                } catch(Exception e) {  
                    e.printStackTrace();  
                } finally {  
                    try {  
                        ds.close();  
                    } catch(Exception e) {  
                        e.printStackTrace();  
                    }  
                }  
            
        }
        
    }
    
    
    }
    MainActivity.java

    前台:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        >
    <!-- 获取输入框信息并发送出去 -->
        <EditText
            android:id="@+id/mEditText"
            android:layout_width="fill_parent"
            android:layout_height="40dp"
            android:cursorVisible="false"
            android:editable="true" 
            
            android:ems="10" >
        </EditText>
         <TextView
            android:id="@+id/mTextView"
            android:layout_width="fill_parent"
            android:layout_height="50dp"
            
            android:ems="10" >
    
        </TextView>
        <Button
            android:id="@+id/mButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="UDP客户端---发送" />
    
    </LinearLayout>
    activity_main.xml

    权限代码:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.simpleclientudp"
        android:versionCode="1"
        android:versionName="1.0" >
    
        <uses-sdk
            android:minSdkVersion="14"
            android:targetSdkVersion="19" />
        <uses-permission android:name="android.permission.INTERNET"/>
    
        <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
            <activity
                android:name=".MainActivity"
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>
    
    </manifest>
    permission.INTERNET

    和TCP的功能类似,也是获取文本框的内容发送,并回显

    所不同的是,改正了PC端显示乱码问题:

    究其原因:安卓这边默认是udf-8编码的

                 PC端是gbk编码的,所以需要:给客户端发送前编码改为utf8,给PC端发送给编码改为gbk

  • 相关阅读:
    设计模式
    DOS批处理脚本
    BAT 批处理脚本 教程
    spring4配置文件详解
    软件过程
    error C2440 “static_cast” 无法从“void (__thiscall C* )(void)...
    error C2065: “IDD_DIALOG1”: 未声明的标识符
    在另一个编辑器中打开
    Github 结合 Hexo 搭建轻量博客
    收藏---wordpress搭建出来的blog
  • 原文地址:https://www.cnblogs.com/shuqingstudy/p/4964105.html
Copyright © 2011-2022 走看看