欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

安卓手机socket通信(服务器和客户端)

程序员文章站 2024-03-07 18:38:45
本文实例为大家分享了安卓手机socket通信代码,供大家参考,具体内容如下 1、socket通信首先要定义好服务端的ip地址和端口号;  (1).首先看服务端...

本文实例为大家分享了安卓手机socket通信代码,供大家参考,具体内容如下

1、socket通信首先要定义好服务端的ip地址和端口号; 

(1).首先看服务端的代码:

package com.example.androidsockettest;

import java.io.bufferedreader;
import java.io.ioexception;
import java.io.inputstream;
import java.io.inputstreamreader;
import java.io.outputstream;
import java.net.serversocket;
import java.net.socket;

import android.net.wifi.wifiinfo;
import android.net.wifi.wifimanager;
import android.os.bundle;
import android.os.handler;
import android.os.message;
import android.app.activity;
import android.content.context;
import android.view.menu;
import android.widget.textview;

public class mainactivity extends activity {

 public static serversocket serversocket = null;
 public static textview mtextview, textview1;
  private string ip = "";
  string buffer = "";
 public static handler mhandler = new handler() {
 @override
 public void handlemessage(android.os.message msg) {
  if (msg.what==0x11) {
  bundle bundle = msg.getdata();
  mtextview.append("client"+bundle.getstring("msg")+"\n");
  }
 };
 };

 @override
 protected void oncreate(bundle savedinstancestate) {
 super.oncreate(savedinstancestate);
 setcontentview(r.layout.activity_main);
 mtextview = (textview) findviewbyid(r.id.textsss);
 textview1 = (textview) findviewbyid(r.id.textview1);
 ip = getlocalip();
 textview1.settext("ip addresss:"+ip);
 new thread() {
  public void run() {
  bundle bundle = new bundle();
  bundle.clear();
  outputstream output;
  string str = "通信成功";
  try {
   serversocket = new serversocket(30000);
   while (true) {
   message msg = new message();
   msg.what = 0x11;
   try {
    socket socket = serversocket.accept();
    output = socket.getoutputstream();
    output.write(str.getbytes("utf-8"));
    output.flush();
    socket.shutdownoutput();
    //mhandler.sendemptymessage(0);
    bufferedreader bff = new bufferedreader(new inputstreamreader(socket.getinputstream()));
    string line = null;
    buffer = "";
    while ((line = bff.readline())!=null) {
    buffer = line + buffer;
    }
    bundle.putstring("msg", buffer.tostring());
    msg.setdata(bundle);
    mhandler.sendmessage(msg);
    bff.close();
    output.close();
    socket.close();
   } catch (ioexception e) {
    e.printstacktrace();
   }
   }
  } catch (ioexception e1) {
   // todo auto-generated catch block
   e1.printstacktrace();
  }
  };
 }.start();
 }
 private string getlocalip(){ 
    wifimanager wifimanager = (wifimanager)getsystemservice(context.wifi_service);  
     wifiinfo wifiinfo = wifimanager.getconnectioninfo();  
     int ipaddress = wifiinfo.getipaddress();  
    // log.d(tag, "int ip "+ipaddress); 
     if(ipaddress==0)return null; 
     return ((ipaddress & 0xff)+"."+(ipaddress>>8 & 0xff)+"." 
        +(ipaddress>>16 & 0xff)+"."+(ipaddress>>24 & 0xff)); 
   } 
 
} 

(2).因为是手机做服务端,所以在开始操作的时候客户端是不知道ip和端口号的,但在服务端运行后就可以看到(亲:你可以自己测试) 

2、客户端的代码 

package com.example.andoroidclient;

import java.io.bufferedreader;
import java.io.ioexception;
import java.io.inputstreamreader;
import java.io.outputstream;
import java.net.inetsocketaddress;
import java.net.socket;
import java.net.sockettimeoutexception;

import android.os.bundle;
import android.os.handler;
import android.os.message;
import android.app.activity;
import android.view.menu;
import android.view.view;
import android.view.view.onclicklistener;
import android.widget.button;
import android.widget.edittext;
import android.widget.textview;

public class mainactivity extends activity {

 socket socket = null;
 string buffer = "";
 textview txt1;
 button send;
 edittext ed1;
 string geted1;
 public handler myhandler = new handler() {
 @override
 public void handlemessage(message msg) {
  if (msg.what == 0x11) {
  bundle bundle = msg.getdata();
  txt1.append("server:" + bundle.getstring("msg") + "\n");
  }
 }

 };

 @override
 protected void oncreate(bundle savedinstancestate) {
 super.oncreate(savedinstancestate);
 setcontentview(r.layout.activity_main);
 txt1 = (textview) findviewbyid(r.id.txt1);
 send = (button) findviewbyid(r.id.send);
 ed1 = (edittext) findviewbyid(r.id.ed1);
 new mythread("建立连接").start();
 send.setonclicklistener(new onclicklistener() {

  @override
  public void onclick(view v) {
  geted1 = ed1.gettext().tostring();
  txt1.append("client:" + geted1 + "\n");
  // 启动线程 向服务器发送和接收信息
  new mythread(geted1).start();
  }
 });

 }

 class mythread extends thread {

 public string txt1;

 public mythread(string str) {
  txt1 = str;
 }

 @override
 public void run() {
  // 定义消息
  message msg = new message();
  msg.what = 0x11;
  bundle bundle = new bundle();
  bundle.clear();
  try {
  // 连接服务器 并设置连接超时为5秒
  socket = new socket();
  socket.connect(new inetsocketaddress("172.20.226.11", 30000), 1000);
  // 获取输入输出流
  outputstream ou = socket.getoutputstream();
  bufferedreader bff = new bufferedreader(new inputstreamreader(socket.getinputstream()));
  // 读取发来服务器信息
  string line = null;
  buffer = "";
  while ((line = bff.readline()) != null) {
   buffer = line + buffer;
  }

  // 向服务器发送信息
  ou.write(txt1.getbytes("gbk"));
  ou.flush();
  bundle.putstring("msg", buffer.tostring());
  msg.setdata(bundle);
  // 发送消息 修改ui线程中的组件
  myhandler.sendmessage(msg);
  // 关闭各种输入输出流
  bff.close();
  ou.close();
  socket.close();
  } catch (sockettimeoutexception aa) {
  // 连接超时 在ui界面显示消息
  bundle.putstring("msg", "服务器连接失败!请检查网络是否打开");
  msg.setdata(bundle);
  // 发送消息 修改ui线程中的组件
  myhandler.sendmessage(msg);
  } catch (ioexception e) {
  e.printstacktrace();
  }
 }
 }

}

3、最后别忘记加网络权限

  <uses-permission android:name="android.permission.internet" />

源码下载:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。