Android socket通過UDP的方式傳送,接收資料
阿新 • • 發佈:2019-02-10
Android socket通過UDP的方式來發送和接收資料,從而進行手機間的通訊。
傳送方:
public class SendToAIUIUtils {
private static InetAddress mAddress;
private static DatagramSocket socket = null;
private static String ip = "255.255.255.255"; //傳送給整個區域網
private static final int SendPort = 9999; //傳送方和接收方需要埠一致
public static void sendContextToAIUI(final Context context, final String content) {
//初始化socket
try {
socket = new DatagramSocket();
} catch (SocketException e) {
e.printStackTrace();
}
try {
mAddress = InetAddress.getByName(ip);
} catch (UnknownHostException e) {
e.printStackTrace();
}
//建立執行緒傳送資訊
new Thread() {
private byte[] sendBuf;
public void run() {
try {
sendBuf = content.getBytes("utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
DatagramPacket recvPacket1 = new DatagramPacket(sendBuf, sendBuf.length, mAddress, SendPort);
try {
socket.send(recvPacket1);
socket.close();
Log.e("zziafyc", "已將內容傳送給了AIUI端內容為:" + content);
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
}
接收端:
public class ReceiveUtils {
private DatagramSocket socket;
private static final int PhonePort = 9999;//手機埠號
private DatagramPacket packet;
private volatile boolean stopReceiver;
String filePath = "/sdcard/AIUI/devices.txt";
private void receiveMessage() {
new Thread() {
public void run() {
try {
socket = new DatagramSocket(PhonePort);
} catch (SocketException e) {
e.printStackTrace();
}
byte[] receBuf = new byte[1024];
packet = new DatagramPacket(receBuf, receBuf.length);
while (!stopReceiver) {
try {
socket.receive(packet);
String receive = new String(packet.getData(), 0, packet.getLength(), "utf-8");
Log.e("zziafyc", "收到的內容為:" + receive);
if (receive.contains("account") || receive.contains("gateWayId")) {
saveSharePreference(receive);
} else {
saveToFile(receive, filePath);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}.start();
}
}
public void saveSharePreference(String receive) {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(receive);
if (receive.contains("account")) {
SharePreferenceUtils.put(this, "account", jsonObject.getString("account"));
SharePreferenceUtils.put(this, "password", jsonObject.getString("password"));
} else {
SharePreferenceUtils.put(this, "gateWayId", jsonObject.getString("gateWayId"));
SharePreferenceUtils.put(this, "gateWayName", jsonObject.getString("gateWayName"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void saveToFile(String str, String filePath) {
try {
File file = new File(filePath);
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream outStream = new FileOutputStream(file);
outStream.write(str.getBytes());
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}