当前位置: 移动技术网 > IT编程>移动开发>Android > Android中Socket的应用分析

Android中Socket的应用分析

2019年07月24日  | 移动技术网IT编程  | 我要评论

环氧涂料,秒客网,杨蕴秋

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网