關(guān)于TCP和UDP協(xié)議的描述,可參考http://zhoujianghai.iteye.com/blog/1052970
下面是android與PC端使用TCP和UDP協(xié)議通信的例子:
以PC端作為服務(wù)器,android端使用TCP協(xié)議與服務(wù)器建立連接,使用UDP協(xié)議接受和發(fā)送數(shù)據(jù)。
服務(wù)器端代碼:
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“跟服務(wù)器端接收到的不一樣,為了避免了使用UDP通信時(shí),android客戶端接收不到server發(fā)送的數(shù)據(jù)的問(wèn)題,server端根據(jù)接收到的數(shù)據(jù)得出發(fā)送數(shù)據(jù)包的客戶端的ip地址和端口,不需要進(jìn)行端口的轉(zhuǎn)發(fā),真機(jī)和模擬器一樣。代碼:
- String clientIp = (packet.getAddress().toString().split("/")[1]);
- for(Client c:clients) {
-
- if(clientIp.trim().equals(c.IP) && c.udpPort == 0) {
- c.setUdpPort(packet.getPort());
- }
- }