您的位置:首页 > 移动开发 > Android开发

Android socket通过UDP的方式发送,接收数据

2017-10-31 17:10 585 查看
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();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: