1. 程式人生 > >Android簡單實現Socket通訊,客戶端連線伺服器後,伺服器向客戶端傳送文字資料

Android簡單實現Socket通訊,客戶端連線伺服器後,伺服器向客戶端傳送文字資料

案例實現的是簡單的Socket通訊,當客戶端(Android客戶端)連線到指定伺服器以後,伺服器向客戶端傳送一句話文字資訊(你可以拓展其它的了) 先看一下服務端程式的實現吧 Server.java
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub

// 建立一個ServerSocket,用於監聽客戶端socket的連線請求
ServerSocket ss = new ServerSocket(30000);
// 採用迴圈不斷接受來自客戶端的請求,伺服器端也對應產生一個Socket
while (true) {
Socket s = ss.accept();
OutputStream os = s.getOutputStream();
os.write("你好,因為你上線了,所以伺服器發給了你這條資訊".getBytes("utf-8"));
os.close();
s.close();
}

}
}
接下來實現的就是手機客戶端的上線並接收資料了,看一下 MainActivity.java
package com.example.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
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 MainActivity extends Activity {
private TextView display;
private Handler handler;
private String host;
private Button btn;
private Socket socket;
private String line;
private EditText et;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler();
btn = (Button) findViewById(R.id.send);
et = (EditText)findViewById(R.id.editText1);
et.setText("192.168.1.100");
OnClickListener listener = new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new Thread() {
public void run() {
try {
host = et.getText().toString();
socket = new Socket(host, 30000);
// 設定10秒之後即認為是超時
socket.setSoTimeout(10000);

BufferedReader br = new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
line = br.readLine();
Log.d("Read:", line);

br.close();
socket.close();

} catch (UnknownHostException e) {
// TODO Auto-generated catch block
Log.e("UnknownHost", "沒找到主機");
e.printStackTrace();
} catch (IOException e) {
Log.e("IOException", "輸入輸出出現錯誤");
// TODO Auto-generated catch block
e.printStackTrace();
}
handler.post(new Runnable(){

@Override
public void run() {
// TODO Auto-generated method stub
display = (TextView) findViewById(R.id.display);
display.setText(line);
}});
}
}.start();
}
};
btn.setOnClickListener(listener);
}
}
這裡需要注意的是,與網路相關的更新UI介面的一定不以在主執行緒中進行更,必須要用到Handler實現UI更新 好了,看一下佈局檔案
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<TextView
android:id="@+id/display"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world" />

<Button
android:id="@+id/send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="72dp"
android:text="Link to Server" />

<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="18dp"
android:ems="10" >

<requestFocus />
</EditText>

</RelativeLayout>

 
最後,不得不提的是,因為用到了網路,所以在AndroidMainFest.xml中千萬不要忘記加上以下許可權
<uses-permission android:name="android.permission.INTERNET" />