简单学习了一个Socket通信的Demo,对Socket建立通信有了一定的了解,先将自己实现的代码贴到这里,有兴趣的同学可以自行下载拷贝。
服务器端代码:
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;
/**
* 服务端
*/
public class TCPServerService extends Service {
private boolean mIsServiceDestoryed = false;
private String[] mDefinedMessages = new String[]{
"你好啊,哈哈",
"请问你叫什么名字?",
"今天天气如何啊?",
"我叫服务器",
"你好老司机"
};
@Override
public void onCreate() {
new Thread(new TcpServer()).start();
super.onCreate();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
/**
* 服务端线程
*/
private class TcpServer implements Runnable {
@Override
public void run() {
ServerSocket serverSocket = null;
try {
// 监听8188端口
serverSocket = new ServerSocket(8188);
} catch (IOException e) {
System.err.println("establis tcp server failed,port:8688");
e.printStackTrace();
return;
}
// 不断接收客户端的消息
while (!mIsServiceDestoryed) {
try {
// 返回一个响应客户端的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()));
// 用于向客户端发送消息
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("用户已离开");
// 关闭流
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);
// 开启服务
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("连接服务器成功");
} catch (IOException e) {
SystemClock.sleep(1000);
System.out.println("连接服务器失败, 再次尝试...");
e.printStackTrace();
}
}
// 接收服务端的消息
try {
BufferedReader in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
// 界面没有关闭就一直接收服务端的消息
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();
}
}
// 客户端界面关闭
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不仅仅能实现进程间的通信,还可以实现设备间的通信。所以最近看见很多Android开发都在要求熟悉Socket协议。关于与硬件设备间的通信各位同学请自行学习了解吧。