簡單學(xué)習(xí)了一個Socket通信的Demo岔冀,對Socket建立通信有了一定的了解,先將自己實現(xiàn)的代碼貼到這里萤厅,有興趣的同學(xué)可以自行下載拷貝目代。
服務(wù)器端代碼:
package cn.ucai.testsocket;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
/**
* 服務(wù)端
*/
public class TCPServerService extends Service {
private boolean mIsServiceDestoryed = false;
private String[] mDefinedMessages = new String[]{
"你好啊,哈哈",
"請問你叫什么名字点弯?",
"今天天氣如何吧鹊鳌?",
"我叫服務(wù)器",
"你好老司機"
};
@Override
public void onCreate() {
new Thread(new TcpServer()).start();
super.onCreate();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
/**
* 服務(wù)端線程
*/
private class TcpServer implements Runnable {
@Override
public void run() {
ServerSocket serverSocket = null;
try {
// 監(jiān)聽8188端口
serverSocket = new ServerSocket(8188);
} catch (IOException e) {
System.err.println("establis tcp server failed,port:8688");
e.printStackTrace();
return;
}
// 不斷接收客戶端的消息
while (!mIsServiceDestoryed) {
try {
// 返回一個響應(yīng)客戶端的Socket
final Socket client = serverSocket.accept();
System.out.print("accept connection");
new Thread(){
@Override
public void run() {
try {
responseClient(client);
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void responseClient(Socket client) throws IOException{
// 接收客戶端的消息
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
// 用于向客戶端發(fā)送消息
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(client.getOutputStream())), true);
out.println("歡迎來到聊天室!");
while (!mIsServiceDestoryed) {
String str = in.readLine();
System.out.println("msg from client:" + str);
if (str == null) {
// 客戶端斷開連接
break;
}
int i = new Random().nextInt(mDefinedMessages.length);
String msg = mDefinedMessages[i];
out.println(msg);
System.out.println("send:" + msg);
}
System.out.println("用戶已離開");
// 關(guān)閉流
Utils.close(in);
Utils.close(out);
client.close();
}
}
客戶端的代碼:
package cn.ucai.testsocket;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
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.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
private static final int MESSAGE_SOCKET_CONNECTED = 0;
private static final int MESSAGE_RECEIVE_NEW_MSG = 1;
private TextView mTvShow;
private EditText mEt;
private Button mBtn;
private Socket mClientSocket;
private PrintWriter mPrintWriter;
@SuppressLint("HandlerLeak")
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_SOCKET_CONNECTED:
mBtn.setEnabled(true);
break;
case MESSAGE_RECEIVE_NEW_MSG:
mTvShow.setText(mTvShow.getText() + (String)msg.obj);
break;
default:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTvShow = (TextView) findViewById(R.id.tv_show);
mEt = (EditText) findViewById(R.id.et);
mBtn = (Button) findViewById(R.id.btn_send);
// 開啟服務(wù)
Intent intent = new Intent(this, TCPServerService.class);
startService(intent);
new Thread() {
@Override
public void run() {
connectTCPServer();
}
}.start();
}
private void connectTCPServer() {
Socket socket = null;
// 如果連接不上就嘗試不斷連接
while (socket == null) {
try {
// 客戶端的Socket
socket = new Socket("localhost", 8188);
mClientSocket = socket;
mPrintWriter = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),true);
mHandler.sendEmptyMessage(MESSAGE_SOCKET_CONNECTED);
System.out.println("連接服務(wù)器成功");
} catch (IOException e) {
SystemClock.sleep(1000);
System.out.println("連接服務(wù)器失敗, 再次嘗試...");
e.printStackTrace();
}
}
// 接收服務(wù)端的消息
try {
BufferedReader in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
// 界面沒有關(guān)閉就一直接收服務(wù)端的消息
while (!MainActivity.this.isFinishing()) {
String msg = in.readLine();
System.out.println("receive:" + msg);
if (msg != null) {
String time = formatDataTime(System.currentTimeMillis());
final String showedMsg = "server " + time + ":" + msg + "\n";
mHandler.obtainMessage(MESSAGE_RECEIVE_NEW_MSG, showedMsg)
.sendToTarget();
}
}
// 客戶端界面關(guān)閉
System.out.println("quit...");
Utils.close(mPrintWriter);
Utils.close(in);
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@SuppressLint("SimpleDateFormat")
private String formatDataTime(long timeMillis) {
return new SimpleDateFormat("(HH:mm:ss)").format(new Date(timeMillis));
}
public void sendMsg(View view) {
String msg = mEt.getText().toString();
if (!TextUtils.isEmpty(msg) && mPrintWriter != null) {
mPrintWriter.println(msg);
mEt.setText("");
String time = formatDataTime(System.currentTimeMillis());
final String showedMsg = "self " + time + ":" + msg + "\n";
mTvShow.setText(mTvShow.getText() + showedMsg);
}
}
@Override
protected void onDestroy() {
if (mClientSocket != null) {
try {
mClientSocket.shutdownInput();
mClientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
super.onDestroy();
}
}
通過Socket不僅僅能實現(xiàn)進程間的通信抢肛,還可以實現(xiàn)設(shè)備間的通信狼钮。所以最近看見很多Android開發(fā)都在要求熟悉Socket協(xié)議。關(guān)于與硬件設(shè)備間的通信各位同學(xué)請自行學(xué)習(xí)了解吧捡絮。