Android uses UDP to transmit data, which causes Chinese garbled characters. Android udp
Recently, the company needs to develop towards the smart home industry. We need to use UDP to transmit data and find some information on the Internet. However, we found garbled Characters During Chinese transmission, the problem is finally solved. The following is the key code.
Client:
1 public class UDPClient { 2 private static final int SERVER_PORT = 6000; 3 private DatagramSocket dSocket = null; 4 private String msg; 5 private String ip; 6 7 public UDPClient(String msg, String ip) { 8 super(); 9 this.msg = msg;10 this.ip = ip;11 }12 13 public void send() {14 try {15 dSocket = new DatagramSocket();16 byte[] bys = msg.getBytes();17 int len = bys.length;18 DatagramPacket dp = new DatagramPacket(bys, len, InetAddress.getByName(ip), SERVER_PORT);19 dSocket.send(dp);20 // }21 } catch (Exception e) {22 // TODO Auto-generated catch block23 e.printStackTrace();24 } finally {25 dSocket.close();26 }27 }28 }
Server:
public class UDPServer implements Runnable {private static final int PORT = 6000;private byte[] msg = new byte[2048];Context context;public UDPServer(Context context) {this.context = context;}@Overridepublic void run() {DatagramSocket s;try {s = new DatagramSocket(PORT);while (true) {int len = msg.length;DatagramPacket dp = new DatagramPacket(msg, len);s.receive(dp);byte[] byc = dp.getData();int len2 = dp.getLength();String ss = new String(byc, 0, len2);Message msg = Message.obtain();msg.what = 0x789;msg.obj = ss;MainActivity.handler.sendMessage(msg);}} catch (Exception e) {e.printStackTrace();}}}