Android中Socket的应用分析

所属分类: 软件编程 / Android 阅读数: 32
收藏 0 赞 0 分享

本文实例分析了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程序设计有所帮助。

更多精彩内容其他人还在看

Android设计登录界面、找回密码、注册功能

这篇文章主要为大家详细介绍了Android设计登录界面的方法,Android实现找回密码、注册功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

Android通过手势实现答题器翻页效果

这篇文章主要为大家详细介绍了Android通过手势实现答题器翻页效果,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

Android采用双缓冲技术实现画板

这篇文章主要为大家详细介绍了Android采用双缓冲技术实现画板的相关资料,思路清晰,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

Android开发之毛玻璃效果实例代码

这篇文章主要给大家分享android开发之毛玻璃效果的实例代码,非常具有参考借鉴价值,感兴趣的朋友一起学习吧
收藏 0 赞 0 分享

Android实现桌面悬浮窗、蒙板效果实例代码

这篇文章主要介绍了Android实现桌面悬浮窗、蒙板效果实例代码的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享

深入解读Android的Volley库的功能结构

这篇文章主要介绍了Android的Volley开发框架的功能结构,Volley是Android开发中网络部分的一大利器,包含很多HTTP协议通信的相关操作,需要的朋友可以参考下
收藏 0 赞 0 分享

Android开发中使用Volley库发送HTTP请求的实例教程

这篇文章主要介绍了Android开发中使用Volley库发送HTTP请求的实例教程,包括创建Volley单例的基本知识与取消Request请求的技巧等,需要的朋友可以参考下
收藏 0 赞 0 分享

Android仿QQ聊天撒花特效 很真实

本文写的这个特效,是关于聊天的,你肯定遇到过,就是你跟人家聊天的时候,比如发送应(么么哒),然后屏幕上全部就是表情了,今天我们就是做这个,撒花的特效,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

Android的HTTP操作库Volley的基本使用教程

这篇文章主要介绍了Android的HTTP操作库Volley的基本使用教程,包括JSON请求与图片加载等用法的实例,需要的朋友可以参考下
收藏 0 赞 0 分享

Android仿水波纹流量球进度条控制器

这篇文章主要介绍了Android仿水波纹流量球进度条控制器的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享
查看更多