天天看點

Android簡單實作Socket通信,client連接配接server後,server向client發送文字資料

案例實作的是簡單的Socket通信,當client(Androidclient)連接配接到指定server以後,server向client發送一句話文字資訊(你能夠拓展其他的了)

先看一下服務端程式的實作吧

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,用于監聽clientsocket的連接配接請求
ServerSocket ss = new ServerSocket(30000);
// 採用循環不斷接受來自client的請求,server端也相應産生一個Socket
while (true) {
Socket s = ss.accept();
OutputStream os = s.getOutputStream();
os.write("你好,由于你上線了,是以server發給了你這條資訊".getBytes("utf-8"));
os.close();
s.close();
}

}
}
      

接下來實作的就是手機client的上線并接收資料了,看一下 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" />