在網絡傳輸中socket是很常見的傳輸方式。
下面介紹一下android中的socket。
socket程式設計一般需要兩個部分,分别為用戶端和伺服器端。
先貼出伺服器端的代碼,具體解釋在代碼中有注釋。由于TCP協定與UDP協定的代碼不同,是以部分代碼注釋起來了,但是都是親測。沒問題的
==========SocketServiceActivity.java=========
package com.yx.socketservice;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class SocketServiceActivity extends Activity {
private Button startButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_socket_service);
startButton = (Button) findViewById(R.id.startButton);
startButton.setOnClickListener(new StartButtonListener());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.socket, menu);
return true;
}
class StartButtonListener implements OnClickListener{
@Override
public void onClick(View arg0) {
new ServerThread().start();//開啟線程
}
}
class ServerThread extends Thread{
@Override
public void run() {//TCP接收
//聲明一個serverSocket對象
ServerSocket serverSocket = null;
try {
//建立serverSocket對象,并讓socket監聽3333端口
serverSocket = new ServerSocket(3333);
//調用serverSocker的accept方法,接收用戶端發送的請求
Socket socket = serverSocket.accept();
//擷取inputstream
InputStream inputStream = socket.getInputStream();
byte[] buffer = new byte[1024*4];
int temp = 0;
while((temp=inputStream.read(buffer))!=-1){
System.out.println(new String(buffer,0,temp));
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
=================AndroidManifest.xml===========
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.yx.socketservice"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.yx.socketservice.SocketServiceActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET"></uses-permission><!-- 一定要有這句,權限的設定 -->
</manifest>
以上是伺服器端的代碼,下面兩個是用戶端的代碼,用戶端僅僅是一個main函數,簡單的java工程。
TCP:
package com.yx.forAnrdoid;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class TCPClient {
public static void main(String[] args) {
OutputStream outputStream=null;
try {
//建立socket對象,指定伺服器的ip和端口
Socket socket = new Socket("192.168.0.100", 3333);
//使用InputStream讀取硬碟上的檔案
InputStream inputStream = new FileInputStream("C://Users/Administrator/Desktop/aa.txt");
//從socket中擷取outputstream
outputStream = socket.getOutputStream();//注意這裡outputstream的包不要倒錯
byte[] buffer = new byte[4*1024];
int temp = 0;
//将inputstream當中的資料取出,并寫入到outputstream中
while((temp=inputStream.read(buffer))!=-1){
outputStream.write(buffer, 0, temp);
}
outputStream.flush();
} catch (Exception e) {
e.printStackTrace();
} finally{
try {
outputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
UDP:
package com.yx.forAnrdoid;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class UDPClient {
public static void main(String[] args) {
try {
//建立一個DatagramSocket對象,并指定監聽端口
DatagramSocket socket = new DatagramSocket(3333);
//建立一個InetAddress
InetAddress serverAddress = InetAddress.getByName("192.168.0.100");
String str = "hello";
byte data[] = str.getBytes();
//建立一個DatagramPacket對象,并指定要将那個資料包發送到那個網絡和端口上
DatagramPacket packet = new DatagramPacket(data, data.length, serverAddress, 3333);
socket.send(packet);
} catch (Exception e) {
e.printStackTrace();
}
}
}