上次讲到android虚拟机和pc机进行通讯,现在就将小程序复杂一点点。
pc将获得的数据原封不动得再发给android虚拟机。
示例图:
[img]http://dl.iteye.com/upload/attachment/558271/c2d21c8c-005b-387f-9ddc-6bb5a0f23c2e.png[/img]
代码在原来的基础上进行了补充:
android端的client:
不解android虚拟机的IP设定。
pc将获得的数据原封不动得再发给android虚拟机。
示例图:
[img]http://dl.iteye.com/upload/attachment/558271/c2d21c8c-005b-387f-9ddc-6bb5a0f23c2e.png[/img]
代码在原来的基础上进行了补充:
public class Server {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
DatagramSocket ds = new DatagramSocket(10000);
while(true){
byte [] b = new byte[1024];
DatagramPacket dp = new DatagramPacket(b,b.length);
ds.receive(dp);
System.out.println("IP: "+dp.getSocketAddress());//输出内容:IP: /127.0.0.1:56934
System.out.println("prot: "+dp.getPort());
System.out.println("data: "+new String(dp.getData(),0,dp.getLength(),"utf-8"));
// 上面和前一篇文章内容一样。只是多了一个server端的send。dp.getSocketAddress()这个就是获取android的Inetaddress
DatagramPacket dp2 = new DatagramPacket(dp.getData(), dp.getLength(), dp.getSocketAddress());
ds.send(dp2);
}
}
}
android端的client:
public class AndroidUdpActivity extends Activity {
DatagramSocket ds = null;
DatagramPacket dp,dp2 = null;
Button b = null;
EditText et = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b = (Button) this.findViewById(R.id.button1);
et = (EditText) this.findViewById(R.id.editText1);
try {
ds = new DatagramSocket(10001);
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
b.setOnClickListener(new OnClickListener() {
// TODO Auto-generated method stub
@Override
public void onClick(View v) {
// String s = "welcome to c....";
String s = et.getText().toString();
byte [] buf = s.getBytes();
int length = buf.length;
try {
dp = new DatagramPacket(buf,length,InetAddress.getByName("10.0.2.2"),10000);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
ds.send(dp);
et.setText("");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//黑体字处为在以前代码上新加的内容,即解析获得的内容。
[b]
byte [] data = new byte[1024];
dp2 = new DatagramPacket(data, data.length);
try {
ds.receive(dp2);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//这里可以获得PC机上的IP,端口等信息。
System.out.println("IP: " + dp2.getSocketAddress());//输出内容: IP: 10.0.2.2/10.0.2.2:10000
try {
System.out.println("data: "+new String(dp2.getData(),0,dp2.getLength(),"utf-8"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//ds.close();
[/b]
}
});
}
}
不解android虚拟机的IP设定。