安卓手機socket通訊(伺服器和用戶端)_Android

來源:互聯網
上載者:User

本文執行個體為大家分享了安卓手機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" />

源碼下載:http://xiazai.jb51.net/201608/yuanma/android-socket(jb51.net).rar

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.