UDP通信工具
package com.dobot.androidtools.Tools;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UdpMessageTool {
private byte[] bytes = new byte[2048];
// DatagramSocket代表UDP協(xié)議的Socket,作用就是接收和發(fā)送數(shù)據(jù)報(bào)
private DatagramSocket mDatagramSocket = null;
public static UdpMessageTool instance;
/**
* 創(chuàng)建UdpMessageTool對(duì)象
*
* @throws Exception
*/
public UdpMessageTool() throws Exception {
// 初始化DatagramSocket,也可以傳入指定端口號(hào)
mDatagramSocket = new DatagramSocket();
}
/**
* 設(shè)置超時(shí)時(shí)間
*/
public final void setTimeOut(final int timeout) throws Exception {
mDatagramSocket.setSoTimeout(timeout);
}
/**
* 獲取DatagramSocket對(duì)象
*/
public final DatagramSocket getDatagramSocket() {
return mDatagramSocket;
}
/**
* 指定的服務(wù)端發(fā)送數(shù)據(jù)信息. 參數(shù)介紹: host 服務(wù)器主機(jī)地址 port 服務(wù)端端口 bytes 發(fā)送的數(shù)據(jù)信息
*/
public final synchronized void send(final String host, final int port, final byte[] bytes) throws IOException {
DatagramPacket dp = new DatagramPacket(bytes, bytes.length, InetAddress.getByName(host), port);
mDatagramSocket.send(dp);
}
/**
* 接收從指定的服務(wù)端發(fā)回的數(shù)據(jù). hostName 服務(wù)端主機(jī) hostPort 服務(wù)端端口 return 服務(wù)端發(fā)回的數(shù)據(jù).
*
* @param hostName
* @param hostPort
* @return
*/
public final synchronized String receive(final String hostName,
final int hostPort) {
DatagramPacket dp = new DatagramPacket(bytes, bytes.length);
try {
mDatagramSocket.receive(dp);
} catch (Exception e) {
e.printStackTrace();
return "";
}
String result = new String(dp.getData(), 0, dp.getLength());
return result;
}
/**
* 關(guān)閉udp連接
*/
public final void close() {
if (mDatagramSocket != null) {
try {
mDatagramSocket.close();
} catch (Exception ex) {
ex.printStackTrace();
}
mDatagramSocket = null;
}
}
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者