zxing的源程序中,将CaptureActivity.java
TextView contentsTextView = (TextView) findViewById(R.id.contents_text_view); CharSequence displayContents = resultHandler.getDisplayContents(); contentsTextView.setText(displayContents);
这一段下面插入一下代码,作为客户端:
new Register().execute(displayContents); private class Register extends AsyncTask<CharSequence, Object, Object> { String addr = "192.168.1.108"; int port = 4444; private DatagramSocket ds; @Override protected Object doInBackground(CharSequence... arg0) { // TODO Auto-generated method stub byte[] data = arg0[0].toString().getBytes(); DatagramPacket dp = null; try { try { ds = new DatagramSocket(port); } catch (SocketException e) { // TODO Auto-generated catch block e.printStackTrace(); } InetAddress ip = InetAddress.getByName(addr); dp = new DatagramPacket(data, data.length, ip, port); dp.setAddress(ip); dp.setData(data); dp.setLength(data.length); System.out.println(ip.toString()); } catch (UnknownHostException e1) { // TODO Auto-generated catch block System.out.println("new packet failed"); } try { ds.send(dp); } catch (IOException e) { // TODO Auto-generated catch block System.out.println("send failed"); } return null; } }
这里面
byte[] data = arg0[0].toString().getBytes();意思是获取二维码扫描的数据是吗?
写了这个之后,server端应该怎么写呢?下面的这一段变异没有问题,但是运行的时候发现与客户端没有连上,是数据没有获取到吗?
import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketAddress; import java.nio.ByteBuffer; public class Server { public static void main(String[] args) { try { //确定接受方的IP和端口号,IP地址为本地机器地址 InetAddress ip = InetAddress.getLocalHost(); int port = 8888; //创建接收方的套接字,并制定端口号和IP地址 DatagramSocket getSocket = new DatagramSocket(port,ip); //确定数据报接受的数据的数组大小 byte[] data = new byte[1024]; // byte[] data = args[0].toString().getBytes(); //创建接受类型的数据报,数据将存储在buf中 DatagramPacket getPacket = new DatagramPacket(data,data.length); //通过套接字接收数据 getSocket.receive(getPacket); //ByteBuffer bbuf = ByteBuffer.wrap(data, 0, 4); //解析发送方传递的消息,并打印 String getMes = new String(data,0,getPacket.getLength()); System.out.println("对方发送的消息:"+getMes); //通过数据报得到发送方的IP和端口号,并打印 InetAddress sendIP = getPacket.getAddress(); int sendPort = getPacket.getPort(); System.out.println("对方的IP地址是:"+sendIP.getHostAddress()); System.out.println("对方的端口号是:"+sendPort); //通过数据报得到发送方的套接字地址 SocketAddress sendAddress = getPacket.getSocketAddress(); //确定要反馈发送方的消息内容,并转换为字节数组 String feedback = "接收方说:我收到了!"; byte[] backBuf = feedback.getBytes(); //创建发送类型的数据报 DatagramPacket sendPacket = new DatagramPacket(backBuf,backBuf.length,sendAddress); //通过套接字发送数据 getSocket.send(sendPacket); //关闭套接字 getSocket.close(); } catch (Exception e) { e.printStackTrace(); } } }
恳请各位帮忙,急!!