前言
在上篇我们讲过了android上upd客户端的实现
,那么接下来,我们讲讲Android上UDP服务端
的实现吧。
大家如果想了解android上upd客户端的实现
的话,可以参考以下文章:
Android上实现UDP客户端
这里我将UDP服务端
的实现封装到了一个类——UdpServer
中,下面就来讲讲它的使用吧。
今天涉及内容:
-
UdpServer
主要方法介绍 -
UdpServer
在主函数中的使用 - 效果图和项目结构图
-
UdpServer
源码
先来波效果图


一. UdpServer主要方法介绍
UdpServer
作为一个UDP
服务端封装类,具备以下几个主要方法:
/**构造函数,绑定主机和端口**/
public UdpServer(int port)
/***
* 服务端给客户端回复消息
*
* @param message 要发送的字符串
* @param charsetName 字符集,如 TcpConfig.UTF_8 或 TcpConfig.GBK,为null时采用编译器默认字符集
*/
public void sendMessage(String message,String charsetName)
/**
* 接收数据包,该方法会造成线程阻塞
*
* @param charsetName 字符集,如 TcpConfig.UTF_8 或 TcpConfig.GBK,为null时采用编译器默认字符集
* @return
*/
public String receiveMessage(String charsetName)
/**关闭数据报服务端socket**/
public void close()
二. UdpServer在主函数中的使用
下面贴出UdpServer
在主函数中使用的代码:
public class TestJava {
public static void main(String[] args) {
UdpServer server=new UdpServer(12345);
while (true){
String message=server.receiveMessage("UTF-8");
System.out.println("======收到消息===message="+message);
String kk="东方一点儿一点opkelpo儿泛着鱼肚色的天空," +
"飘着五颜六色的朝霞,有:降紫的、金黄的、青色的……甚至还有一些火红色的火烧云," +
"好像把大半个天给点燃,简直就是美不胜收。今天的朝霞十分奇异,既不像棉花糖," +
"又不像绵羊,而像鱼鳞,很罕见,如果把蓝天比作大海,那这朝霞就是海浪,令人陶醉。" +
"在东南方向,还有一道七色彩虹,像桥一样,也许是太阳公公的桥梁吧!";
//发送消息
server.sendMessage(kk,"UTF-8");
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
三.效果图和项目结构图



四. UdpServer 源码
下面贴出UdpServer
源码:
网友评论