公司最近需要往智能家居方面發展,需要用到UDP協議傳輸數據,在網上找到了一些資料,但是發現傳輸中文的時候有亂碼的現象,經過我多番搗鼓,終於解決了這個問題,下麵貼上關鍵代碼 客戶端: 服務端: ...
公司最近需要往智能家居方面發展,需要用到UDP協議傳輸數據,在網上找到了一些資料,但是發現傳輸中文的時候有亂碼的現象,經過我多番搗鼓,終於解決了這個問題,下麵貼上關鍵代碼
客戶端:
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 block 23 e.printStackTrace(); 24 } finally { 25 dSocket.close(); 26 } 27 } 28 }
服務端:
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; } @Override public 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(); } } }