关于TCP和UDP协议的描述,可参考http://zhoujianghai.iteye.com/blog/1052970
下面是android与PC端使用TCP和UDP协议通信的例子:
以PC端作为服务器,android端使用TCP协议与服务器建立连接,使用UDP协议接受和发送数据。
服务器端代码:
ThunderServer.java
客户端的核心代码:
public void connectServer(String IP,int port) {
- this.IP = IP;
-
- try {
- socket = new DatagramSocket(udpPort);
- } catch (SocketException e) {
- e.printStackTrace();
- }
-
- Socket s = null;
- try {
- s = new Socket(IP,port);
- System.out.println("s="+s);
-
- DataInputStream dis = new DataInputStream(s.getInputStream());
- int id = dis.readInt();
- System.out.println("id="+id);
-
- } catch (UnknownHostException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }finally {
- if(s != null) {
- try {
- s.close();
- s = null;
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- this.IP = IP;
-
- try {
- socket = new DatagramSocket(udpPort);
- } catch (SocketException e) {
- e.printStackTrace();
- }
-
- Socket s = null;
- try {
- s = new Socket(IP,port);
- System.out.println("s="+s);
-
- DataInputStream dis = new DataInputStream(s.getInputStream());
- int id = dis.readInt();
- System.out.println("id="+id);
-
- } catch (UnknownHostException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }finally {
- if(s != null) {
- try {
- s.close();
- s = null;
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
客户端代码绑定的UDP端口”udpPort“跟服务器端接收到的不一样,为了避免了使用UDP通信时,android客户端接收不到server发送的数据的问题,server端根据接收到的数据得出发送数据包的客户端的ip地址和端口,不需要进行端口的转发,真机和模拟器一样。代码:
- String clientIp = (packet.getAddress().toString().split("/")[1]);
- for(Client c:clients) {
-
- if(clientIp.trim().equals(c.IP) && c.udpPort == 0) {
- c.setUdpPort(packet.getPort());
- }
- }