Android中Socket的应用分析

Android中Socket的应用分析,第1张

概述本文实例分析了Android中Socket的应用。分享给大家供大家参考,具体如下:Android提供的常用的网络编程包括针对TCP/IP协议的Socket通信。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 = "";@OverrIDepublic 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中Socket的应用分析全部内容,希望文章能够帮你解决Android中Socket的应用分析所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1147961.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-31
下一篇2022-05-31

发表评论

登录后才能评论

评论列表(0条)

    保存