Socket
其实和JavaWeb 里面的Socket一模一样
建立客服端,服务器端,服务器开一个端口供客服端访问
第一步创建服务器端:(这里把为了便于讲解,把服务器端,和客服端都放在手机上了)
创建Android工程
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());//把相当于客服端数据写到服务器端 //虚拟机(手机)相当于一个电脑127.0.0.1是访问手机自己,9999是服务器开的端口号 } 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(); } } } } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-11-07 22:23:54