Android 提供的常用的网络编程包括针对TCP/IP协议的Socket通信。Socket是一种跨平台的编程方式,可以在异构语言之间进行通信。
Socket程序的开发原理,是要实现服务器端和客户端。
服务器,使用ServerSocket监听指定的端口,端口可以随意指定(由于1024以下的端口通常属于保留端口,在一些操作系统中不可以随意使用,所以建议使用大于1024的端口),等待客户连接请求,客户连接后,会话产生;在完成会话后,关闭连接。
客户端,使用Socket对网络上某一个服务器的某一个端口发出连接请求,一旦连接成功,打开会话;会话完成后,关闭Socket。客户端不需要指定打开的端口,通常临时的、动态的分配一个1024以上的端口。
下面是一个实现socket的例子:
服务器端代码:
- packagecom.socket;
- importjava.io.BufferedReader;
- importjava.io.InputStream;
- importjava.io.InputStreamReader;
- importjava.io.OutputStream;
- importjava.io.PrintWriter;
- importjava.net.ServerSocket;
- importjava.net.Socket;
- /**
- *comServer
- */
- publicclassMain{
- privateintServerPort=9999;
- privateServerSocketserversocket=null;
- privateOutputStreamoutputStream=null;
- privateInputStreaminputStream=null;
- privatePrintWriterprintWinter=null;
- privateSocketsocket=null;
- privateBufferedReaderreader=null;
- publicMain(){
- try{
- serversocket=newServerSocket(ServerPort);
- System.out.println("服务启动。。。");
- socket=serversocket.accept();
- System.out.println("客户已连接");
- }catch(Exceptionex){
- ex.printStackTrace();
- }
- try{
- outputStream=socket.getOutputStream();
- inputStream=socket.getInputStream();
- printWinter=newPrintWriter(outputStream,true);
- reader=newBufferedReader(newInputStreamReader(inputStream));
- BufferedReaderin=newBufferedReader(newInputStreamReader(System.in));
- while(true){
- Stringmessage=reader.readLine();
- System.out.println("client:"+message);
- if(message.equals("bye")||message.equals("Bye")){
- break;
- }
- message=in.readLine();
- printWinter.println(message);
- }
- outputStream.close();
- inputStream.close();
- socket.close();
- serversocket.close();
- System.out.print("Clientisdisconnected");
- }catch(Exceptione){
- e.printStackTrace();
- }finally{
- }
- }
- publicstaticvoidmain(String[]args){
- newMain();
- }
客服端代码:
- packagecom.Aina.Android;
- importjava.io.BufferedReader;
- importjava.io.BufferedWriter;
- importjava.io.InputStreamReader;
- importjava.io.OutputStreamWriter;
- importjava.io.PrintWriter;
- importjava.net.Socket;
- importandroid.app.Activity;
- importandroid.app.AlertDialog;
- importandroid.content.DialogInterface;
- importandroid.os.Bundle;
- importandroid.os.Handler;
- importandroid.os.Message;
- importandroid.util.Log;
- importandroid.view.View;
- importandroid.widget.Button;
- importandroid.widget.EditText;
- importandroid.widget.TextView;
- publicclassTestextendsActivityimplementsRunnable{
- /**Calledwhentheactivityisfirstcreated.*/
- privateTextViewtv_msg=null;
- privateEditTexted_msg=null;
- privateButtonbtn_send=null;
- privateButtonbtn_login=null;
- privatestaticfinalStringHOST="192.168.0.132";
- privatestaticfinalintPORT=9999;
- privateSocketsocket=null;
- privateBufferedReaderin=null;
- privatePrintWriterout=null;
- privateStringcontent="";
- @Override
- publicvoidonCreate(BundlesavedInstanceState){
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- tv_msg=(TextView)this.findViewById(R.id.TextView);
- ed_msg=(EditText)this.findViewById(R.id.EditText01);
- btn_login=(Button)this.findViewById(R.id.Button01);
- btn_send=(Button)this.findViewById(R.id.Button02);
- try{
- socket=newSocket(HOST,PORT);
- in=newBufferedReader(newInputStreamReader(socket
- .getInputStream()));
- out=newPrintWriter(newBufferedWriter(
- newOutputStreamWriter(socket.getOutputStream())),
- true);
- }catch(Exceptionex){
- ex.printStackTrace();
- ShowDialog("登陆异常:"+ex.getMessage());
- }
- btn_send.setOnClickListener(newButton.OnClickListener(){
- publicvoidonClick(Viewv){
- //TODOAuto-generatedmethodstub
- Stringmsg=ed_msg.getText().toString();
- if(socket.isConnected()){
- if(!socket.isOutputShutdown()){
- out.println(msg);
- }
- }
- }
- });
- newThread(this).start();
- }
- publicvoidShowDialog(Stringmsg){
- newAlertDialog.Builder(this).setTitle("提示").setMessage(msg)
- .setPositiveButton("OK",newDialogInterface.OnClickListener(){
- publicvoidonClick(DialogInterfacedialog,intwhich){
- //TODOAuto-generatedmethodstub
- }
- }).show();
- }
- publicvoidrun(){
- try{
- while(true){
- if(socket.isConnected()){
- if(!socket.isInputShutdown()){
- if((content=in.readLine())!=null){
- Log.i("TAG","++"+content);
- content+="\n";
- mHandler.sendMessage(mHandler.obtainMessage());
- }else{
- }
- }
- }
- }
- }catch(Exceptionex){
- ex.printStackTrace();
- }
- }
- publicHandlermHandler=newHandler(){
- publicvoidhandleMessage(Messagemsg){
- super.handleMessage(msg);
- Log.i("TAG","--"+msg);
- tv_msg.setText(tv_msg.getText().toString()+content);
- }
- };
- }
XML文件布局:
- <?xmlversion="1.0"encoding="utf-8"?>
- <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"android:layout_width="fill_parent"
- android:layout_height="fill_parent">
- <TextViewandroid:id="@+id/TextView"android:singleLine="false"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"/>
- <EditTextandroid:hint="content"android:id="@+id/EditText01"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content">
- </EditText>
- <Buttonandroid:text="login"android:id="@+id/Button01"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content">
- </Button>
- <Buttonandroid:text="send"android:id="@+id/Button02"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content">
- </Button>
- </LinearLayout>
先启动服务器端,再运行客户端程序。
注意:(一)即使服务器端和客户端在一台机器上运行,也不能使用ip地址:127.0.0.1,否则,程序会出现拒绝连接的错误。
(二)客户端和服务器端最好不要建在一个工程下,最好是分别建立工程,然后启动服务器端和客户端,否则会报Error: ShouldNotReachHere()错误。这是因为Android程序不是已main方法为程序的入口。
运行效果:
XML文件布局:
- <?xmlversion="1.0"encoding="utf-8"?>
- <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"android:layout_width="fill_parent"
- android:layout_height="fill_parent">
- <TextViewandroid:id="@+id/TextView"android:singleLine="false"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"/>
- <EditTextandroid:hint="content"android:id="@+id/EditText01"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content">
- </EditText>
- <Buttonandroid:text="login"android:id="@+id/Button01"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content">
- </Button>
- <Buttonandroid:text="send"android:id="@+id/Button02"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content">
- </Button>
- </LinearLayout>
先启动服务器端,再运行客户端程序。
注意:(一)即使服务器端和客户端在一台机器上运行,也不能使用ip地址:127.0.0.1,否则,程序会出现拒绝连接的错误。
(二)客户端和服务器端最好不要建在一个工程下,最好是分别建立工程,然后启动服务器端和客户端,否则会报Error: ShouldNotReachHere()错误。这是因为Android程序不是已main方法为程序的入口。
运行效果: