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

参考别人一幅原理图。

 

 

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;
	}
	
}


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值