安卓手機socket通信(服務(wù)器和客戶端)
本文實例為大家分享了安卓手機socket通信代碼,供大家參考,具體內(nèi)容如下
1、socket通信首先要定義好服務(wù)端的ip地址和端口號;
(1).首先看服務(wù)端的代碼:
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).因為是手機做服務(wù)端,所以在開始操作的時候客戶端是不知道ip和端口號的,但在服務(wù)端運行后就可以看到(親:你可以自己測試)
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");
// 啟動線程 向服務(wù)器發(fā)送和接收信息
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 {
// 連接服務(wù)器 并設(shè)置連接超時為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()));
// 讀取發(fā)來服務(wù)器信息
String line = null;
buffer = "";
while ((line = bff.readLine()) != null) {
buffer = line + buffer;
}
// 向服務(wù)器發(fā)送信息
ou.write(txt1.getBytes("gbk"));
ou.flush();
bundle.putString("msg", buffer.toString());
msg.setData(bundle);
// 發(fā)送消息 修改UI線程中的組件
myHandler.sendMessage(msg);
// 關(guān)閉各種輸入輸出流
bff.close();
ou.close();
socket.close();
} catch (SocketTimeoutException aa) {
// 連接超時 在UI界面顯示消息
bundle.putString("msg", "服務(wù)器連接失??!請檢查網(wǎng)絡(luò)是否打開");
msg.setData(bundle);
// 發(fā)送消息 修改UI線程中的組件
myHandler.sendMessage(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
3、最后別忘記加網(wǎng)絡(luò)權(quán)限
<uses-permission android:name="android.permission.INTERNET" />
源碼下載:http://xiazai.jb51.net/201608/yuanma/android-socket(jb51.net).rar
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Android Socket通信詳解
- Android編程之客戶端通過socket與服務(wù)器通信的方法
- Android中Socket通信的實現(xiàn)方法概述
- Java實現(xiàn)的基于socket通信的實例代碼
- Java Socket通信(一)之客戶端程序 發(fā)送和接收數(shù)據(jù)
- Java Web項目中使用Socket通信多線程、長連接的方法
- Android中使用socket通信實現(xiàn)消息推送的方法詳解
- Android開發(fā)中Socket通信的基本實現(xiàn)方法講解
- Android基于socket實現(xiàn)的簡單C/S聊天通信功能
- Android中socketpair雙向通信詳解
相關(guān)文章
Android中實現(xiàn)根據(jù)資源名獲取資源ID
這篇文章主要介紹了Android中實現(xiàn)根據(jù)資源名獲取資源ID,本文講解了使用文件名獲取資源ID的方法,需要的朋友可以參考下2015-01-01
android基礎(chǔ)教程之a(chǎn)ndroid的listview與edittext沖突解決方法
這篇文章主要介紹了android的listview與edittext沖突解決方法,需要的朋友可以參考下2014-02-02
Android中利用NetworkInfo判斷網(wǎng)絡(luò)狀態(tài)時出現(xiàn)空指針(NullPointerException)問題的解決
這篇文章主要介紹了Android中利用NetworkInfo判斷網(wǎng)絡(luò)狀態(tài)時出現(xiàn)空指針(NullPointerException)問題的解決方法,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-11-11
AndroidStudio 配置 AspectJ 環(huán)境實現(xiàn)AOP的方法
本篇文章主要介紹了AndroidStudio 配置 AspectJ 環(huán)境實現(xiàn)AOP的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-02-02
android判斷phonegap是否聯(lián)網(wǎng)且加載super.loadUrl網(wǎng)址
android判斷phonegap是否聯(lián)網(wǎng)動態(tài)加載super.loadUrl網(wǎng)址,接下來本文所提供的知識會幫助你解決以上問題,感興趣的你可不要錯過了哈2013-02-02
詳談android 6.0 fuse文件系統(tǒng)的掛載和卸載問題
今天小編就為大家分享一篇詳談android 6.0 fuse文件系統(tǒng)的掛載和卸載問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08

