android学习笔记18--------------UDP示例

参考别人一幅原理图。

 android学习笔记18--------------UDP示例_第1张图片

android学习笔记18--------------UDP示例_第2张图片

 

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

public class UDPClient
{
	private DatagramSocket client=null;
	private DatagramPacket packet=null;
	private InetAddress host=null;
	public static int portSend=8888;
	public static String name="192.168.142.199";
	
	
	public UDPClient()
	{		
		try
		{
			host = InetAddress.getByName(name);
			client=new DatagramSocket();
										
			System.out.println("客户端准备就绪");
		} catch (Exception e)
		{
			e.printStackTrace();
		} 							
	}
	
	public void UDPClientRun(byte[] buffer) throws IOException	
	{								
		host = InetAddress.getByName(name);
		packet=new DatagramPacket(buffer,buffer.length, host, portSend);
		client.send(packet);	
		System.out.println("客户端发送消息");
	}
	
	public void UDPClientStop()
	{
		client.close();
	}
}


 

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UDPService
{
	private DatagramSocket server =null;
	private DatagramPacket dPacket=null;
	private byte[] buffer = new byte[640];	
	public static int portServer=8888;
	
	public UDPService ()
	{
		try
		{
			server  = new DatagramSocket(portServer);	
			dPacket = new DatagramPacket(buffer, buffer.length);
		} catch (Exception e)
		{
			e.printStackTrace();
		}		    
	}
	
	public byte[] UDPServiceRun()
	{																							
		try
		{
			server.receive(dPacket);
			System.out.println("服务端接收到消息");
		} catch (IOException e)
		{
			e.printStackTrace();
			System.out.println("服务端未收到消息");
		}							
		return buffer;						
	}
	
	public void UDPSeverStop()
	{
		server.close();
	}
	
	public String getClientName()
	{
		String name="";
		name=dPacket.getAddress().toString();
		return name;
	}
	
}


 


原文链接: http://blog.csdn.net/yf210yf/article/details/6954975

你可能感兴趣的:(android学习笔记18--------------UDP示例)