Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android網絡編程之Socket通信

Android網絡編程之Socket通信

編輯:關於Android編程

Socket(套接字)是一種通信機制,可以實現單機或跨網絡進行通信,其創建需要明確的區分C(客戶端)/S(服務器端),支持多個客戶端連接到同一個服務器。有兩種傳輸模式:

1)、面向連接的傳輸:基於TCP協議,可靠性高,但效率低;

2)、面向無連接的傳輸:基於UDP協議,可靠性低,但效率高;

Android中,直接采用Socket通信應該是我們遇到的最低級的網絡運用。盡管已經作了很大程度的抽象,但是純粹的Socket通信,仍然給開發者留下很多細節需要處理,尤其在服務器端,開發者需要處理多線程以及數據緩沖等的設計問題。相對而言,處於更高抽象層的HTTP等,已經對Socket通信中需要處理的技術細節進行了很好的封裝,開發者無須關心,因此,HTTP在網絡開發中通常具有決定性的優勢。

Android在其核心庫的java包中,提供了用於客戶端的Socket class和用於服務器端的ServerSocket class,分別位於$SOURCE/libcore/luni/src/main/java/java/net/Socket.java和$SOURCE/libcore/luni/src/main/java/java/net/ServerSocket.java文件中。分析兩個class的源碼,可以看出封裝考慮的很全面,只構造方法一向每個class都考慮了很多種使用情況。由於本人只是初學者,很多理解的不深入,這裡只拋磚引玉的對兩個class的構造方法分別介紹一種,就是我下面的程序中用到的:

Socket(String dstName, int dstPort):創建一個以流的方式(基於TCP協議)連接到目標機(這裡可以理解為服務器)的客戶端Socket;dstName是目標機的IP地址,dstPort是要連接的目標機的端 口號。這裡要注意對端口的理解,它不能理解為物理上的一個接口,而是對計算機中一塊特殊內存區域的形象表述。

ServerSocket(int aport):創建一個綁定到本機指定端口的服務端Socket;aport就是指定的本機端口。與上述客戶端Socket對應,通過TCP連接時,ServerSocket創建後需要在aport端口上進行監聽,等待客戶端的連接。

 

啟動 service 和 activity

 

mContext.startService(new Intent(mContext, SocketService.class));

Intent intent = new Intent();
intent.setClass(mContext, SocketClientDemo.class);
mContext.startActivity(intent);

 

service :服務端

package com.android.settings;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class SocketService extends Service {
Thread mServiceThread;

Socket client;

@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}

@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();

mServiceThread = new Thread(new SocketServerThread());
}

@Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);

mServiceThread.start();
}

@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}

public class SocketServerThread extends Thread {
private static final int PORT = 54321;

private SocketServerThread() {
}

@Override
public void run() {
try {
ServerSocket server = new ServerSocket(PORT);

while (true) {
System.out.println("tian begin client connected");
client = server.accept();
System.out.println(" tian client connected");

BufferedReader reader = new BufferedReader(
new InputStreamReader(client.getInputStream()));
System.out.println(" tian read from client:");

String textLine = reader.readLine();
if (textLine.equalsIgnoreCase("EXIT")) {
System.out
.println(" tian EXIT invoked, closing client");
break;
}

System.out.println(textLine);

PrintWriter writer = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(client.getOutputStream())));

System.out.println(" return tian read from client:"
+ textLine);
writer.println(" tian ECHO from server: " + textLine);
writer.flush();

writer.close();
reader.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
System.err.println(e);
}
}

}
}

 

package com.android.settings;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class SocketClientDemo extends Activity {
private static final String SERVERIP = "127.0.0.1";
private static final int SERVERPORT = 54321;

private static final String TAG = "SocketClientDemo";

TextView mMsgRev;
EditText mMsgEdit;
Button mMsgSendBtn;

String mSendMsg;
String mReceivedMsg;

class MyThread implements Runnable {
private String name;

public MyThread(String name) {
this.name = name;
}

public void run() {
// for (int i = 0; i < 100; i++) {
// System.out.println("線程開始:" + this.name + ",i=" + i);

Log.d(TAG, "MyThread execu");
// }
}
};

class MyThread2 extends Thread {

@Override
public void run() {
// TODO Auto-generated method stub
Log.d(TAG, "MyThread2 execu");
}
};

class MyThread3 extends Thread {

private String name;

public MyThread3(String name) {
// super();
this.name = name;
}

@Override
public void run() {
// TODO Auto-generated method stub
Log.d(TAG, "MyThread3 execu" + "name=" + name);

Socket socket = null;
mSendMsg = mMsgEdit.getText().toString();

try {
socket = new Socket(SERVERIP, SERVERPORT);

PrintWriter writer = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())));
writer.println(mSendMsg);
writer.flush();

BufferedReader reader = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
mReceivedMsg = reader.readLine();

Message meaage = mHander.obtainMessage();
meaage.arg1 = 1;
mHander.sendMessage(meaage);

writer.close();
reader.close();
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.xml.beidou_detail_preference_settings);

mMsgRev = (TextView) findViewById(R.id.receive_msg);
mMsgEdit = (EditText) findViewById(R.id.edit_msg);
mMsgSendBtn = (Button) findViewById(R.id.send_msg);

mMsgSendBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {

/*
* MyThread thread = new MyThread("00"); new
* Thread(thread).start();
*
* new MyThread2().start();
*/

MyThread3 thread3 = new MyThread3("33");
thread3.start();

}
});
}

final Handler mHander = new Handler() {

@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub

if (mReceivedMsg != null) {
mMsgRev.setText(mReceivedMsg);
} else {
mMsgRev.setText("tian receive data error");
}
super.handleMessage(msg);
}

};
}

 

activity : 客戶端

 

package com.android.settings;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class SocketClientDemo extends Activity {
private static final String SERVERIP = "127.0.0.1";
private static final int SERVERPORT = 54321;

private static final String TAG = "SocketClientDemo";

TextView mMsgRev;
EditText mMsgEdit;
Button mMsgSendBtn;

String mSendMsg;
String mReceivedMsg;

class MyThread implements Runnable {
private String name;

public MyThread(String name) {
this.name = name;
}

public void run() {
// for (int i = 0; i < 100; i++) {
// System.out.println("線程開始:" + this.name + ",i=" + i);

Log.d(TAG, "MyThread execu");
// }
}
};

class MyThread2 extends Thread {

@Override
public void run() {
// TODO Auto-generated method stub
Log.d(TAG, "MyThread2 execu");
}
};

class MyThread3 extends Thread {

private String name;

public MyThread3(String name) {
// super();
this.name = name;
}

@Override
public void run() {
// TODO Auto-generated method stub
Log.d(TAG, "MyThread3 execu" + "name=" + name);

Socket socket = null;
mSendMsg = mMsgEdit.getText().toString();

try {
socket = new Socket(SERVERIP, SERVERPORT);

PrintWriter writer = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())));
writer.println(mSendMsg);
writer.flush();

BufferedReader reader = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
mReceivedMsg = reader.readLine();

Message meaage = mHander.obtainMessage();
meaage.arg1 = 1;
mHander.sendMessage(meaage);

writer.close();
reader.close();
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.xml.beidou_detail_preference_settings);

mMsgRev = (TextView) findViewById(R.id.receive_msg);
mMsgEdit = (EditText) findViewById(R.id.edit_msg);
mMsgSendBtn = (Button) findViewById(R.id.send_msg);

mMsgSendBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {

/*
* MyThread thread = new MyThread("00"); new
* Thread(thread).start();
*
* new MyThread2().start();
*/

MyThread3 thread3 = new MyThread3("33");
thread3.start();

}
});
}

final Handler mHander = new Handler() {

@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub

if (mReceivedMsg != null) {
mMsgRev.setText(mReceivedMsg);
} else {
mMsgRev.setText("tian receive data error");
}
super.handleMessage(msg);
}

};
}

 

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved