如何在Android平台下进行Socket通信

 首先在Java se平台上新建一个Socket服务端:

public static void main(String[] args) {
  try {
   ServerSocket ss = new ServerSocket(8888);
   System.out.println("Listening");
   while(true) {
    Socket socket = ss.accept(); //获取连接的Socket对象
    System.out.println("Wati!Client Connected...");
    DataOutputStream dout = new DataOutputStream(socket.getOutputStream());
    Date d = new Date();//创建一个data对象
    dout.writeUTF(d.toLocaleString());//向客户端发送日期信息
    dout.close();//关闭DataOutputStream
    socket.close();//关闭Socket对象
   }
  } catch (IOException e) { 
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

完成了服务端之后,再在andorid平台下新建一个客户端

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        connectionToServer();
    }
    
    public void connectionToServer(){
     try {
   Socket scoket = new Socket("10.167.18.140",8888);
   DataInputStream din = new DataInputStream(scoket.getInputStream());//获取输入流
   
   String msg =din.readUTF();//读取服务端发送的消息
   EditText et = (EditText) findViewById(R.id.et_client);
   et.setText(msg);
   
  } catch (UnknownHostException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
    }

在完成了客户端之后还必须在mainfest.xml文件中加入网络权限

<uses-permission android:name="android.permission.INTERNET"/>

然后就是先运行服务端,在项目名上单击右键,选择Run As Java Appliacation

再在Android上运行客户端即可,此时就可以看到在客户端的输入框中看到服务端的系统时间了

你可能感兴趣的:(socket通信)