編輯:關於Android編程
本文實例為大家分享了安卓手機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
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持本站。
AVD的全稱為:Android Virtual Device,就是Android運行的虛擬設備,他是Android的模擬器識別。建立的Android要運行,必須創建AVD
一、終於到最後一個組件了。首先運行一個Demo吧,這個Demo是在網上找的,自己修改了點:1.ContentproviderDemoActivity演示類,用戶獲取Con
本文實例講述了Android普通對話框用法。分享給大家供大家參考。具體如下:main.xml布局文件:<?xml version=1.0 encoding=
1. Adapter.getView() public View getView(int position, View convertView , ViewGroup p