整个流程为:点击连接按钮后,客户端请求与服务器连接,同时开启接受数据的新线程。成功后可在文本框里输入发送的内容,点击发送则发送,同时程序可以不断地接收服务器信息。
下面在讲述几点比较坑的点:
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();
}
}
}