问题描述
- android应用开发在创建DatagramSocket对象时绑定不 了端口
-
package com.example.clientudp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
private Button fasong =null;
private static final int PORT=4328;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fasong=(Button)findViewById(R.id.kaishi);
fasong.setOnClickListener(new kaishianniu());
}
class kaishianniu implements OnClickListener{
public void onClick(View arg0) {
xianCheng s=new xianCheng();
Thread aa=new Thread(s);
aa.start();
}
}
//关键语句:://///////////////////////////////////////////////////////////////////////
class xianCheng implements Runnable{@Override public void run() { // TODO Auto-generated method stub try{ System.out.println("chuangjian"); DatagramSocket socket =new DatagramSocket(PORT); System.out.println("套接字创建成功"); System.out.println(socket.getPort()); InetAddress address=InetAddress.getByName("10.16.6.32"); String str="hello"; byte data[]=str.getBytes(); System.out.println(socket.getPort()); DatagramPacket packet=new DatagramPacket(data, data.length,address,PORT); System.out.println(socket.getPort()); socket.send(packet); socket.close(); System.out.println("发送成功"); }catch(IOException e){ System.out.println("fail"); e.printStackTrace(); System.out.println(e.getMessage()); } } }
}、
////////////////////////////////////////////////////////////////////////////
使用真机测试结果:
服务器代码::
package UDP;import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;public class myUDP {
public static void main(String[] args) {
xianCheng a=new xianCheng();
Thread th=new Thread(a);
th.start();
}
}
class xianCheng implements Runnable{public void run() { // TODO Auto-generated method stub try{ System.out.println("chuangjian"); DatagramSocket socket=new DatagramSocket(); System.out.println("server ok"); byte buffer[] =new byte [1024]; DatagramPacket packet=new DatagramPacket(buffer, buffer.length); System.out.println("等待接受"); socket.receive(packet); System.out.println("receive ok"); String result = new String(packet.getData(),packet.getOffset(),packet.getLength()); System.out.println("you enter is ->"+result); socket.close(); }catch(IOException e){ System.out.println("server fail"); e.printStackTrace(); } }
}
上面是服务器端代码,虽然真机显示发送成功,但是服务器端没有接收到数据包,求各位大神指点迷津???
解决方案
你服务端没有绑定端口
解决方案二:
你服务端没有绑定端口
时间: 2024-10-03 22:48:05