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();
}
}
}
上面是服務器端代碼,雖然真機顯示發送成功,但是服務器端沒有接收到數據包,求各位大神指點迷津???
你服務端沒有綁定端口