Android uses UDP to transmit data, which causes Chinese garbled characters. Android udp

Source: Internet
Author: User

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();}}}

  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.