手机使用GPRS网络与server进行Socket通信,代码下载地址:
用UDP协议与Socket调试工具进行測试。
SocketActivity.java:
package com.example.socket;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;import android.os.Bundle;import android.app.Activity;import android.view.View;import android.widget.Button;import android.view.View.OnClickListener;public class SocketActivity extends Activity { private Button startButton = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_socket); startButton = (Button)findViewById(R.id.startListener); startButton.setOnClickListener(new StartSocketListener()); } class StartSocketListener implements OnClickListener{ @Override public void onClick(View v){ new ServerThread().start(); } } class ServerThread extends Thread{ public void run(){ try{ DatagramSocket socket = new DatagramSocket(1234); InetAddress serverAddress = InetAddress.getByName("115.238.249.92"); String str = "hello"; byte data[] = str.getBytes(); DatagramPacket packet = new DatagramPacket(data,data.length,serverAddress,1234); socket.send(packet); }catch (Exception e) { e.printStackTrace(); } } }}activity_socket.xml:
Socket调试工具创建UDP Server监听1234port,本机IP为115.238.249.92。
安装执行apk,按下Sendbutton。server端收到数据。
注意在AndroidManifest.xml中加入: