Socket UPD接收数据出现乱码

时间:2022-12-15 16:29:36
 
 
 
 
package com.xu.servlet;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

//发送请求的代码
public class Snippet
{
	public static void main(String[] args)
	{
		System.out.println("---------");
		Snippet snippet = new Snippet();
		
		
		snippet.Test();
	}
	
	
	public void Test()
	{
		
		//1、创建socket对象,通过DatagramSocket对象
        DatagramSocket ds = null;
		try
		{
			ds = new DatagramSocket();
			
		} catch (SocketException e) 
		{
			e.printStackTrace();
		}
        String serverIP = "";
        String socketPort ="";
        JSONObject jsonObject = new JSONObject();
        try 
        {
			/*jsonObject.put("type", "openDoor");
	        jsonObject.put("doorId", "1");
	        jsonObject.put("interval", "20");*/

			jsonObject.put("type", "closeDoor");
	        jsonObject.put("doorId", "1");
	        jsonObject.put("interval", "20");
		} catch (JSONException e1) {
			e1.printStackTrace();
		}

        //2、确定数据,并封装成数据包
        byte[]  data = jsonObject.toString().getBytes();
        DatagramPacket dp = null;
		try 
		{
			dp = new DatagramPacket(data, data.length, InetAddress.getByName("192.168.32.24"), 8086);
			
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}

        //3、通过scoket服务,将已有的数据发送出去,通过send方法
        try {
        	
        	System.out.println(" dp =  "+ dp);
			ds.send(dp);
		} catch (IOException e) 
        {
			e.printStackTrace();
		}
        ds.close();
	}
}
//接收数据	
class AccZonePersonSaveThread extends Thread
	{

		@Override
		public void run()
		{
			 DatagramSocket ds = null;

			System.out.println("---------");
			try
			{
				ds = new DatagramSocket(8088);
			}
			catch (SocketException e1)
			{
				e1.printStackTrace();
			}
			while (true)
			{
				try
				{
					 //2、定义数据包,用于存储数据
				    byte[] buf = new byte[1024];
				    DatagramPacket dp = new DatagramPacket(buf, buf.length);
				
				    //3、通过服务的receive方法,接收数据并存入数据包中
						ds.receive(dp);
				
				    //4、通过数据包中的方法,获取其中的数据。
				    String ip = dp.getAddress().getHostAddress();
				    int port = dp.getPort();
				    String data = new String(dp.getData(),"GBK");
				    System.out.println("ip = " + ip + ": " + port + ":   " + data);
				  
				}
				catch (SocketException e)
				{
					e.printStackTrace();
				}
				catch (IOException e)
				{
					e.printStackTrace();
				}
				   
			}
		
			
		}
		
	}
接收的时候加上
 String data = new String(dp.getData(),"GBK");

就可以了