1. 与Socket交换数据
1.1 知识点
(1)通过Android与Socket完成基本的Echo程序实现;
(2)通过对象序列化进行大数据的传输;
1.2 具体内容
对于网络的开发而言,最常使用的交互模式:WEB Service、WebServer、Socket程序,一些Socket程序的使用是绝对要比JSP/Servlet更加安全的,所有许多android程序手机端会使用Socket进行数据交换。
服务端:(JavaSE项目)
package com.SocketServer;import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;public class MyServer {public static void main(String[] args) throws Exception{ServerSocket server = new ServerSocket(2012); // 在8888端口上监听Socket client = server.accept(); // 接收客户端请求PrintStream out = new PrintStream(client.getOutputStream()); // 取得客户端输出流BufferedReader buf = new BufferedReader(new InputStreamReader(client.getInputStream())); // 字符缓冲区读取StringBuffer info = new StringBuffer(); // 接收客户端的信息info.append("Android : "); // 回应数据info.append(buf.readLine()); // 接收数据out.print(info); // 发送信息out.close(); // 关闭输出流buf.close(); // 关闭输入流client.close(); // 关闭客户端连接server.close(); }
}
客户端布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context=".SocketConnetionActivity" ><Buttonandroid:id="@+id/but"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Echo回应程序"/><TextViewandroid:id="@+id/tv"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="等待服务端发送回应信息。。。。" /></LinearLayout>
客户端:
package com.example.socketconnectionproject;import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;public class SocketConnetionActivity extends Activity {Button but = null;TextView tv = null;String response = null;private Handler handler = new Handler() {@Overridepublic void handleMessage(Message msg) {switch (msg.what) {case 1:SocketConnetionActivity.this.tv.setText(msg.obj.toString());// 接收子线程消息break;}}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_socket_connetion);this.but = (Button) super.findViewById(R.id.but);this.tv = (TextView) super.findViewById(R.id.tv);but.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {new Thread(new Runnable() {@Overridepublic void run() {try {Socket client = new Socket("172.26.64.60", 2012); // 指定服务器PrintStream out = new PrintStream(client.getOutputStream()); // 打印流输出BufferedReader buf = new BufferedReader(new InputStreamReader(client.getInputStream()));out.println("华万通科技有限公司");// 发送数据response = buf.readLine();out.close(); // 关闭输出流buf.close(); // 关闭输入流client.close();// 关闭连接} catch (Exception e) {e.printStackTrace();}Message mag = new Message();mag.what = 1;mag.obj = response;SocketConnetionActivity.this.handler.sendMessage(mag);// 向主线程发送信息}}).start();}});}}
以下实现利用Socket进行登录验证:
服务端:
package com.SocketServer;import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;public class MyServer {public static void main(String[] args) throws Exception{ServerSocket server = new ServerSocket(2012); // 在8888端口上监听Socket client = server.accept(); // 接收客户端请求PrintStream out = new PrintStream(client.getOutputStream()); // 取得客户端输出流BufferedReader buf = new BufferedReader(new InputStreamReader(client.getInputStream())); // 字符缓冲区读取String userInfo = buf.readLine();System.out.println(userInfo);String userStr[] = userInfo.split(",");DH10User user = new DH10User(userStr[0],userStr[1]);boolean bool=new LoginDAOImpl(GetConnection.getConn()).login(user);if(bool){out.print("LoginSuccess"); // 发送信息}else{out.print("LoginFail");}out.close(); // 关闭输出流buf.close(); // 关闭输入流client.close(); // 关闭客户端连接server.close(); }
}
客户端:
package com.example.socketconnectionproject;import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;public class SocketConnetionActivity extends Activity {EditText username,password=null;Button but = null;String response = null;private Handler handler = new Handler() {@Overridepublic void handleMessage(Message msg) {switch (msg.what) {case 1:Toast.makeText(SocketConnetionActivity.this, msg.obj.toString(), 0).show();// 接收子线程消息break;}}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_socket_connetion);this.but = (Button) super.findViewById(R.id.login);this.username = (EditText) super.findViewById(R.id.username);this.password = (EditText) super.findViewById(R.id.password);but.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {new Thread(new Runnable() {@Overridepublic void run() {try {Socket client = new Socket("172.26.64.60", 2012); // 指定服务器PrintStream out = new PrintStream(client.getOutputStream()); // 打印流输出BufferedReader buf = new BufferedReader(new InputStreamReader(client.getInputStream()));out.println(SocketConnetionActivity.this.username.getText().toString()+","+SocketConnetionActivity.this.password.getText().toString());// 发送数据response = buf.readLine();out.close(); // 关闭输出流buf.close(); // 关闭输入流client.close();// 关闭连接} catch (Exception e) {e.printStackTrace();}Message mag = new Message();mag.what = 1;mag.obj = response;SocketConnetionActivity.this.handler.sendMessage(mag);// 向主线程发送信息}}).start();}});}}
1.3 小结
(1)使用Android可以与Socket程序进行通信;
(2)上传文件可以采用序列化的方式简单完成,但是程序不具备通用性;