Android中Socket的应用分析

 更新时间:2016年10月21日 15:38:27   作者:pku_android  
这篇文章主要介绍了Android中Socket的应用,结合实例形式分析了Android中socket通信的实现技巧与相关注意事项,需要的朋友可以参考下

本文实例分析了Android中Socket的应用。分享给大家供大家参考,具体如下:

Android 提供的常用的网络编程包括针对TCP/IP协议的Socket通信。Socket是一种跨平台的编程方式,可以在异构语言之间进行通信。

Socket程序的开发原理,是要实现服务器端和客户端。

服务器,使用ServerSocket监听指定的端口,端口可以随意指定(由于1024以下的端口通常属于保留端口,在一些操作系统中不可以随意使用,所以建议使用大于1024的端口),等待客户连接请求,客户连接后,会话产生;在完成会话后,关闭连接。

客户端,使用Socket对网络上某一个服务器的某一个端口发出连接请求,一旦连接成功,打开会话;会话完成后,关闭Socket。客户端不需要指定打开的端口,通常临时的、动态的分配一个1024以上的端口。

下面是一个实现socket的例子:

服务器端代码:

package com.socket;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
/**
* com Server
*/
public class Main {
  private int ServerPort = 9999;
  private ServerSocket serversocket = null;
  private OutputStream outputStream = null;
  private InputStream inputStream = null;
  private PrintWriter printWinter = null;
  private Socket socket = null;
  private BufferedReader reader = null;
  public Main(){
    try{
      serversocket = new ServerSocket(ServerPort);
      System.out.println("服务启动。。。");
      socket = serversocket.accept();
      System.out.println("客户已连接");
    }catch(Exception ex){
      ex.printStackTrace();
    }
    try{
      outputStream= socket.getOutputStream();
      inputStream = socket.getInputStream();
      printWinter = new PrintWriter(outputStream,true);
      reader = new BufferedReader(new InputStreamReader(inputStream));
      BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
      while (true){
        String message = 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("Client is disconnected");
    }catch(Exception e){
      e.printStackTrace();
    }finally{
    }
  }
  public static void main(String[] args){
    new Main();
  }
}

客服端代码:

package com.Aina.Android;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Test extends Activity implements Runnable {
/** Called when the activity is first created. */
private TextView tv_msg = null;
private EditText ed_msg = null;
private Button btn_send = null;
private Button btn_login = null;
private static final String HOST = "192.168.0.132";
private static final int PORT = 9999;
private Socket socket = null;
private BufferedReader in = null;
private PrintWriter out = null;
private String content = "";
@Override
public void onCreate(Bundle savedInstanceState) {
 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 = new Socket(HOST, PORT);
  in = new BufferedReader(new InputStreamReader(socket
   .getInputStream()));
  out = new PrintWriter(new BufferedWriter(
   new OutputStreamWriter(socket.getOutputStream())),
   true);
 } catch (Exception ex) {
  ex.printStackTrace();
  ShowDialog("登陆异常:" + ex.getMessage());
 }
 btn_send.setOnClickListener(new Button.OnClickListener() {
  public void onClick(View v) {
  // TODO Auto-generated method stub
  String msg = ed_msg.getText().toString();
  if (socket.isConnected()) {
   if (!socket.isOutputShutdown()) {
   out.println(msg);
   }
  }
  }
 });
 new Thread(this).start();
}
public void ShowDialog(String msg) {
 new AlertDialog.Builder(this).setTitle("提示").setMessage(msg)
  .setPositiveButton("OK", new DialogInterface.OnClickListener() {
   public void onClick(DialogInterface dialog, int which) {
   // TODO Auto-generated method stub
   }
  }).show();
}
public void run() {
 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 (Exception ex) {
  ex.printStackTrace();
 }
}
public Handler mHandler = new Handler() {
 public void handleMessage(Message msg) {
  super.handleMessage(msg);
  Log.i("TAG", "-- "+msg);
  tv_msg.setText(tv_msg.getText().toString() + content);
 }
};
}

XML文件布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:id="@+id/TextView" android:singleLine="false"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content" />
<EditText android:hint="content" android:id="@+id/EditText01"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content">
</EditText>
<Button android:text="login" android:id="@+id/Button01"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content">
</Button>
<Button android: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方法为程序的入口。

运行效果:

更多关于Android相关内容感兴趣的读者可查看本站专题:《Android通信方式总结》、《Android调试技巧与常见问题解决方法汇总》、《Android开发入门与进阶教程》、《Android多媒体操作技巧汇总(音频,视频,录音等)》、《Android基本组件用法总结》、《Android视图View技巧总结》、《Android布局layout技巧总结》及《Android控件用法总结

希望本文所述对大家Android程序设计有所帮助。

相关文章

最新评论