整個流程爲:點擊連接按鈕後,客戶端請求與服務器連接,同時開啓接受數據的新線程。成功後可在文本框裏輸入發送的內容,點擊發送則發送,同時程序可以不斷地接收服務器信息。
下面在講述幾點比較坑的點:
1、切忌,一定要在一個新線程中編寫socket,或者添加以下代碼
//*******解決主線程訪問網絡的問題
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork() // or .detectAll() for all detectable problems
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.detectLeakedClosableObjects()
.penaltyLog()
.penaltyDeath()
.build());
// ************
2、在配置文件中添加以下代碼
<uses-permission android:name= "android.permission.INTERNET"/>
3、使用如下代碼傳輸數據時
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
每次發送完數據,一定要調用flush()和close()方法。不然會一直接收不到數據
下面附上完整的代碼
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* Created by liyongqi on 2016/8/7.
*/
public class Client extends Activity
{
private EditText mEditText = null;
private Button connectButton = null;
private Button sendButton = null;
// private TextView mTextView = null;
private Socket clientSocket = null;
private OutputStream outStream = null;
private Handler mHandler = null;
private ReceiveThread mReceiveThread = null;
private boolean stop = true;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.mian);
//*******解決主線程訪問網絡的問題
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork() // or .detectAll() for all detectable problems
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.detectLeakedClosableObjects()
.penaltyLog()
.penaltyDeath()
.build());
// ************
mEditText = (EditText) this.findViewById(R.id.edittext);
// mTextView = (TextView) this.findViewById(R.id.retextview);
connectButton = (Button) this.findViewById(R.id.connectbutton);
sendButton = (Button) this.findViewById(R.id.sendbutton);
sendButton.setEnabled(false);
// 連接按鈕監聽
connectButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
try
{
// 實例化對象並連接到服務器
clientSocket = new Socket("192.168.1.157",8889);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.d("Client","連接成功");
// 連接按鈕使能
connectButton.setEnabled(false);
// 發送按鈕使能
sendButton.setEnabled(true);
mReceiveThread = new ReceiveThread(clientSocket);
stop = false;
// 開啓線程
mReceiveThread.start();
}
});
//發送數據按鈕監聽
sendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
BufferedWriter bufferedWriter=null;
try {
bufferedWriter = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
} catch (IOException e) {
Log.d("Client","BufferedWriter出錯");
e.printStackTrace();
}
// 獲得EditTex的內容
String text = mEditText.getText().toString();
Log.d("Client","即將發送的信息爲:"+text);
try {
// 發送數據
bufferedWriter.write(text);
bufferedWriter.flush();
bufferedWriter.close();
} catch (IOException e) {
Log.d("Client","發送數據出錯");
e.printStackTrace();
}
Log.d("Client","成功發送數據");
// 清空內容
mEditText.setText("");
}
});
}
private class ReceiveThread extends Thread
{
private BufferedReader in = null;
private String str = null;
ReceiveThread(Socket s) {
try {
// 獲得輸入流
in = new BufferedReader(new InputStreamReader(s.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (!stop) {
// 讀取輸入的數據(阻塞讀)
try {
String s=in.readLine();
Log.d("Client",s);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
@Override
public void onDestroy() {
super.onDestroy();
if (mReceiveThread != null) {
stop = true;
mReceiveThread.interrupt();
}
}
}