我使用以下代码从特定端口接收数据.它不适用于Android.但是将数据发送到特定端口工作正常.
public class UDPDemo extends Activity { private TextView tv; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); tv = (TextView)findViewById(R.id.recv_message); try { DatagramSocket clientsocket=new DatagramSocket(9876); byte[] receivedata = new byte[1024]; while(true) { DatagramPacket recv_packet = new DatagramPacket(receivedata, receivedata.length); Log.d("UDP", "S: Receiving..."); clientsocket.receive(recv_packet); String rec_str = new String(recv_packet.getData()); tv.setText(rec_str); Log.d(" Received String ",rec_str); InetAddress ipaddress = recv_packet.getAddress(); int port = recv_packet.getPort(); Log.d("IPAddress : ",ipaddress.toString()); Log.d(" Port : ",Integer.toString(port)); } } catch (Exception e) { Log.e("UDP", "S: Error", e); } } }
ktingle.. 5
如果您使用的是模拟器,则可能需要设置重定向,请记住模拟器位于虚拟路由器后面.
换句话说,键入这些命令;
telnet localhost 5554 redir add udp:9876:9876
然后再试一次.
如果您使用的是模拟器,则可能需要设置重定向,请记住模拟器位于虚拟路由器后面.
换句话说,键入这些命令;
telnet localhost 5554 redir add udp:9876:9876
然后再试一次.