简单收发编码解码UDP协议(一)

MainActivity

package com.example.udpagreement;

import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {
	EditText name_input;
	EditText number_input;
	EditText english_input;
	EditText math_input;
	Button btn_OK;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        name_input = (EditText)this.findViewById(R.id.name);
        number_input = (EditText)this.findViewById(R.id.number);
        english_input = (EditText)this.findViewById(R.id.english);
        math_input = (EditText)this.findViewById(R.id.math);
        
        btn_OK = (Button)this.findViewById(R.id.btn_OK);
        btn_OK.setOnClickListener(new OnClickListener(){
        	byte[] data;
			@Override
			public void onClick(View v) {
				
				data = setUser();
				//改进
				new Thread(){public void run(){
					sendMsg(data);
				}}.start();
			}
        });
    }
    
//    DatagramSocket socket;
    public void sendMsg(byte[] data){
    	Log.i("agreement","client send...");
    	try {
    		DatagramSocket socket = new DatagramSocket(0);
			
			//目标地址
			InetAddress host = InetAddress.getByName("192.168.31.254");
			
			//指定包要发送的目的地
			DatagramPacket request =new DatagramPacket(data,data.length, host, 8082);
			
			//发送
	        socket.send(request);
	        Log.i("agreement","client send success");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.i("agreement", "Error...");
		}
    	
    }
    
    public byte[] setUser(){
    	
    	String name = name_input.getText().toString();
		String number = number_input.getText().toString();
		int english = Integer.parseInt(english_input.getText().toString());
		int math = Integer.parseInt(math_input.getText().toString());
		
		User user = new User();
		user.name = name;
		user.number = number;
		user.english = english;
		user.math = math;
		
		byte[] use_byte = User2bytes(user);
		
		return use_byte;
	}
    
	
    private static int len_name = 6;
    private static int len_number = 10;
	public static byte[] User2bytes(User user){
		String name = user.name;//6字节
		byte[] use_1 = String2bytes(name,len_name);
		
		String number = user.number;//10字节
		byte[] use_2 = String2bytes(number,len_number);
		
		int english = user.english;//4字节
		byte[] use_3 = intToByteArray(english);
		
		int math = user.math;//4字节
		byte[] use_4 = intToByteArray(math);
		
		byte[] use = new byte[24];
		
		//将以上的两个数组复制到下面的use字节数组中去,比较耗时
//		java.util.Arrays.copyOf(arg0, arg1);
		//java.util.Arrays.copy();拷贝数组的函数
		//发送次数,发送时间
		
		for(int i=0;i<use_1.length;i++){
			use[i] = use_1[i];
		}
		
		for(int i=0;i<use_2.length;i++){
			use[i+use_1.length] = use_2[i];
		}
		
		for(int i=0;i<use_3.length;i++){
			use[i+use_1.length+use_2.length] = use_3[i];
		}
		
		for(int i=0;i<use_4.length;i++){
			use[i+use_1.length+use_2.length+use_3.length] = use_4[i];
		}
		
		return use;
	}
	
	
	
    
    /**
	 * 将字符串转换为长度为len的字节数组
	 * @param s
	 * @param len
	 * @return
	 */
	static byte[] data;
	public static byte[] String2bytes(String s,int len){
		byte[] ss;
		try {
			ss = s.getBytes("UTF-8");
			data = new byte[len];
			
			for(int i=0;i<ss.length;i++){
				data[i] = ss[i];
			}
			
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return data;
		
	}
	
	/** 
	 * int到byte[] 
	 * @param i 
	 * @return 
	 */  
	public static byte[] intToByteArray(int i) {  
	    byte[] result = new byte[4];  
	    // 由高位到低位  
	    result[0] = (byte) ((i >> 24) & 0xFF);  
	    result[1] = (byte) ((i >> 16) & 0xFF);  
	    result[2] = (byte) ((i >> 8) & 0xFF);  
	    result[3] = (byte) (i & 0xFF);  
	    return result;  
	}  
	

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
}

UDP_agreement

import java.awt.FlowLayout;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;


public class UDPSever_Agreement extends JFrame{
	
	public static void main(String[] args) {
		UDPSever_Agreement ua = new UDPSever_Agreement();
		ua.initUI();
		receiveSever();
	}
	
	static JTextField name_receive;
	static JTextField number_receive;
	static JTextField english_receive;
	static JTextField math_receive;
	
	static DatagramSocket socket;
	public static void receiveSever(){
		System.out.println("udp recive server start ....");
		
		try {
			socket = new DatagramSocket(8082);
			
			while(true){
			byte[]  receive_data=new byte[24];
			
			DatagramPacket request = new DatagramPacket(receive_data, 24);
				
				//程序很可能会阻塞在这里等待接收消息
				socket.receive(request);
				
				User user = bytes2User(receive_data);
				name_receive.setText(user.name);
				number_receive.setText(user.number);
				english_receive.setText(user.english+"");
				math_receive.setText(user.math+"");
				
				
//				//得到发送方Client的地址
//				address = request.getAddress();
//				System.out.println("发送方地址"+address);
//				port = request.getPort();
//				System.out.println("发送方端口"+port);
				
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	}
	
	private static int len_name = 6;
	private static int len_number = 10;
	public static User bytes2User(byte[] data) throws UnsupportedEncodingException{
		
		User user = new User();
		//-----1--------name------6字节----------
		byte[] use_1 = new byte[len_name];
		for(int i=0;i<use_1.length;i++){
			use_1[i] = data[i];
		}
		String name = new String(use_1,"UTF-8");
		user.name = name;
		
		//-----2--------number-------10字节---------
		byte[] use_2 = new byte[len_number];
		for(int i=0;i<use_2.length;i++){
			use_2[i] = data[i+use_1.length];
		}
		String number = new String(use_2,"UTF-8");
		user.number = number;
		
		//-----3--------english----4字节------
		byte[] use_3 = new byte[4];
		for(int i=0;i<use_3.length;i++){
			use_3[i] = data[i+use_1.length+use_2.length];
		}
		int english = byteArrayToInt(use_3);
		user.english = english;
		
		//-----4--------math----4字节------
		byte[] use_4 = new byte[4];
		for(int i=0;i<use_4.length;i++){
			use_4[i] = data[i+use_1.length+use_2.length+use_3.length];
		}
		int math = byteArrayToInt(use_4);
		user.math = math;
		
		return user;
	}
	
	/** 
	 * byte[]转int 
	 * @param bytes 
	 * @return 
	 */  
	public static int byteArrayToInt(byte[] bytes) {  
	    int value = 0;  
	    // 由高位到低位  
	    for (int i = 0; i < 4; i++) {  
	        int shift = (4 - 1 - i) * 8;  
	        value += (bytes[i] & 0x000000FF) << shift;// 往高位游  
	    }  
	    return value;  
	}  
	
	
    
	
	public void initUI(){
		this.setTitle("PC&Mobile通信");
		this.setSize(500, 180);
		this.setLocationRelativeTo(null);
		this.setDefaultCloseOperation(3);
		this.setLayout(new FlowLayout());
		
		JLabel name1 = new JLabel("姓名");
		name_receive = new JTextField(40);
		this.add(name1);
		this.add(name_receive);
		
		JLabel number1 = new JLabel("学号");
		number_receive = new JTextField(40);
		this.add(number1);
		this.add(number_receive);
		
		JLabel english1 = new JLabel("英语");
		english_receive = new JTextField(40);
		this.add(english1);
		this.add(english_receive);
		
		JLabel math1 = new JLabel("数学");
		math_receive = new JTextField(40);
		this.add(math1);
		this.add(math_receive);
		
		this.setVisible(true);
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_42882887/article/details/86633128
今日推荐