事实上和JavaWeb 里面的Socket一模一样
建立客服端,server端,server开一个port供客服端訪问
第一步创建server端:(这里把为了便于解说。把server端,和客服端都放在手机上了)
创建Androidproject
socketserver
package com.example.socketserver; import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; import android.os.AsyncTask; import android.os.Bundle; import android.app.Activity; import android.view.Menu; /** * 创建服务器端 * * */ public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); AsyncTask.execute(new Runnable() { @Override public void run() { startService();//訪问网络 } }); } /* * 服务器端从客服端 * * */ public void startService(){ Socket socket =null; InputStream inputStream = null; try { ServerSocket serverSocket = new ServerSocket(9999);//填入端口号 socket = serverSocket.accept();//接收客服端的的连接请求 inputStream = socket.getInputStream();//获取输入流 /* * 从输入流中读取数据 * * */ byte[] bs = new byte[1024]; int i=-1; while((i = inputStream.read(bs))!=-1){ System.out.println(new String(bs,0,i)); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(inputStream!=null){ try { inputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(socket!=null) try { socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
第二步搭建Socket客服端
package com.example.socketclient; import java.io.IOException; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; import android.os.AsyncTask; import android.os.Bundle; import android.app.Activity; import android.view.Menu; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); AsyncTask.execute(new Runnable() { @Override public void run() { // TODO Auto-generated method stub startClient(); } }); } public void startClient(){ OutputStream out = null; Socket socket = null; try { socket = new Socket("127.0.0.1",9999); out = socket.getOutputStream();//获取输出流 out.write("abc".getBytes());//把相当于客服端数据写到server端 //虚拟机(手机)相当于一个电脑127.0.0.1是訪问手机自己,9999是server开的端口号 } catch (Exception e) { e.printStackTrace(); } finally{ if(out!=null){ try { out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }//关闭 } if(socket!=null){ try { socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }