Android网络编程Socket【实例解析】

来源:互联网 发布:js bind有什么用 编辑:程序博客网 时间:2024/06/05 19:47
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 {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);AsyncTask.execute(new Runnable() {@Overridepublic 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 blocke.printStackTrace();}finally{if(inputStream!=null){try {inputStream.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}if(socket!=null)try {socket.close();} catch (IOException e) {// TODO Auto-generated catch blocke.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 {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);AsyncTask.execute(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubstartClient();}});}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 blocke.printStackTrace();}//关闭}if(socket!=null){try {socket.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}}




0 0
原创粉丝点击