Android UDP
【摘要】
package com.chy.socket; import java.io.IOException;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.SocketException; import com.chy.global.G...
-
package com.chy.socket;
-
-
import java.io.IOException;
-
import java.net.DatagramPacket;
-
import java.net.DatagramSocket;
-
import java.net.SocketException;
-
-
import com.chy.global.GlobalValue;
-
-
public class UdpClient {
-
-
private boolean isStop = false;
-
private DatagramSocket datagramSocket = null;
-
private onReceiveListener onReceiveListener = null;
-
private ReadThread readThread = null;
-
-
public interface onReceiveListener {
-
public void onReceive(DatagramPacket packet);
-
}
-
-
class ReadThread extends Thread {
-
-
@Override
-
public void run() {
-
byte[] buffer = new byte[GlobalValue.READ_BLOCK_SIZE];
-
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
-
while (!isStop && !isInterrupted()) {
-
try {
-
datagramSocket.receive(packet);
-
if (onReceiveListener != null) {
-
onReceiveListener.onReceive(packet);
-
}
-
} catch (IOException ex) {
-
ex.printStackTrace();
-
}
-
}
-
}
-
-
}
-
-
public UdpClient(int port, onReceiveListener onReceiveListener) {
-
try {
-
datagramSocket = new DatagramSocket(port);
-
} catch (SocketException ex) {
-
ex.printStackTrace();
-
}
-
if (datagramSocket == null) {
-
return;
-
}
-
this.onReceiveListener = onReceiveListener;
-
readThread = new ReadThread();
-
readThread.start();
-
}
-
-
public synchronized boolean send(byte[] buffer) {
-
boolean result = false;
-
if(datagramSocket != null) {
-
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
-
try {
-
datagramSocket.send(packet);
-
result = true;
-
} catch (IOException ex) {
-
ex.printStackTrace();
-
}
-
}
-
return result;
-
}
-
-
public void close() {
-
isStop = true;
-
if(readThread != null && !readThread.isInterrupted()) {
-
readThread.interrupt();
-
readThread = null;
-
}
-
if (datagramSocket != null) {
-
datagramSocket.close();
-
}
-
}
-
}
文章来源: blog.csdn.net,作者:福州-司马懿,版权归原作者所有,如需转载,请联系作者。
原文链接:blog.csdn.net/chy555chy/article/details/51560186
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)