目录
前言
之前记录了Android中Socket的简单使用,也就是对数据的简单收发操作。这简单的对SocketServer进行封装。
记录于此,方便自己查阅。
正文
SocketServer服务端一般不需要我们写,大多数是作为客户端去绑定其他的,比如Tbox。但服务端跟客户端差不多,因此也一起整理一下。
服务端其实主要就是SocketServer这个类的使用,其他的只是封装成一定的接口,方便上层调用而已。 公共类,方便统一修改 开启SocketServer并等待客户端来绑定 接收客户端消息 对SocketServer相关的封装 这个用于回调到上层。 Socket 服务端管理类,封装一些接口。Common.java
public class Common {
public static String IP = "192.168.252.219";//通信的IP地址
public static int PORT = 8888;//可以改
public static final String SOCKET_CHARSET = "gbk";//utf-8
}
ServerThread.java
public class ServerThread extends Thread {
private final String TAG = SocketApp.TAG + getClass().getSimpleName();
private ServerCallback mServerCallback;
private SocketServer mSocketServer;
private volatile boolean mRunning = false;
public ServerThread(SocketServer socketServer, ServerCallback serverCallback) {
mSocketServer = socketServer;
mServerCallback = serverCallback;
}
public void stopRunning() {
Log.d(TAG, "stopRunning: ");
mRunning = false;
}
@Override
public void run() {
super.run();
ServerSocket serverSocket = null;
try {
Log.d(TAG, "ServerThread run start : ");
mRunning = true;
while (mRunning) {
if (null == serverSocket) {
InetAddress inetAddress = InetAddress.getByName(mSocketServer.getIp());
Log.d(TAG, "run inetAddress : " + inetAddress);
//50 表示入栈连接的最大个数
serverSocket = new ServerSocket(mSocketServer.getPort(), 50, inetAddress);
// serverSocket = new ServerSocket(mSocketServer.getPort());
mSocketServer.setServerSocket(serverSocket);
Socket socket = serverSocket.accept(); //等待一个客户端的连接,在连接之前,此方法是阻塞的
mSocketServer.setSocket(socket);
mServerCallback.startSuccess();
}
}
Log.d(TAG, "ServerThread run end : ");
} catch (IOException e) {
e.printStackTrace();
}
mServerCallback.stopSuccess();
}
}
ReceiveThread.java
public class ReceiveThread extends Thread {
private final String TAG = SocketApp.TAG + getClass().getSimpleName();
private final SocketServer mSocketServer;
private volatile boolean mRunning = false;
private final ServerCallback mServerCallback;
public ReceiveThread(SocketServer socketServer, ServerCallback serverCallback) {
mSocketServer = socketServer;
mServerCallback = serverCallback;
}
public void stopRunning() {
Log.d(TAG, "stopRunning: ");
mRunning = false;
}
@Override
public void run() {
super.run();
mRunning = true;
InputStream inputStream = null;
Log.d(TAG, "ReceiveThread run start : ");
while (mRunning && (null == inputStream)) {
try {
if (null != mSocketServer.getSocket()) {
inputStream = mSocketServer.getSocket().getInputStream();
}
} catch (IOException e) {
e.printStackTrace();
}
if (null == inputStream) {
try {
Thread.sleep(30);
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
}
}
while (mRunning) {
try {
byte[] buffer = new byte[1024];
int count = inputStream.read(buffer);
if (count > 0) {
// 防止乱码
String message = new String(buffer, "GBK").trim();
if (!TextUtils.isEmpty(message) && null != mServerCallback) {
mServerCallback.updateMessage(message);
}
}
Thread.sleep(30);
} catch (Exception e) {
e.printStackTrace();
}
}
Log.d(TAG, "ReceiveThread run end : ");
}
}
SocketServer.java
public class SocketServer {
private int port = Common.PORT;
private String ip = Common.IP;
private ServerSocket serverSocket = null;
private Socket socket = null;
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public void setServerSocket(ServerSocket serverSocket) {
this.serverSocket = serverSocket;
}
public Socket getSocket() {
return socket;
}
public void setSocket(Socket socket) {
this.socket = socket;
}
public synchronized void closeSocket() {
if (null != serverSocket) {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
if (null != serverSocket) {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
serverSocket = null;
}
}
socket = null;
}
}
ServerCallback.java
public interface ServerCallback {
void startSuccess();
void stopSuccess();
void updateMessage(String message);
}
IMessageCallback.java
public interface IMessageCallback {
void onMessage(boolean formServer, String message);
void connectStatus(boolean success);
}
ServerManager.java
public class ServerManager implements Handler.Callback, ServerCallback {
private final String TAG = SocketApp.TAG + getClass().getSimpleName();
// 如果是分发数据,可以进行封装使用
private HandlerThread mHandlerThread = null;
private Handler mHandler;
private final int MSG_SEND_DATA = 0x1000;
private final int MSG_START_SERVER = 0x1001;
private final int MSG_STOP_SERVER = 0x1002;
//
private SocketServer mSocketServer = null;
private ReceiveThread mReceiveThread = null;
private ServerThread mServerThread = null;
private boolean mConnect = false;
private OutputStream mOutputStream;
private IMessageCallback mIMessageCallback = null;
private ServerManager() {
//private
}
@Override
public void startSuccess() {
Log.d(TAG, "startSuccess: ");
mConnect = true;
try {
mOutputStream = mSocketServer.getSocket().getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
mReceiveThread.start();
}
@Override
public void stopSuccess() {
mConnect = false;
Log.d(TAG, "stopSuccess: ");
mOutputStream = null;
mIMessageCallback.connectStatus(false);
}
@Override
public void updateMessage(String message) {
Log.d(TAG, "updateMessage message : " + message);
if (null != mIMessageCallback) {
mIMessageCallback.onMessage(false, message);
}
}
private static class SingleHolder {
private static final ServerManager serverManager = new ServerManager();
}
public static ServerManager getInstance() {
return SingleHolder.serverManager;
}
@Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case MSG_SEND_DATA:
Log.d(TAG, "MSG_SEND_DATA mConnect : " + mConnect);
if (mConnect) {
try {
mOutputStream.write(((String) msg.obj).getBytes(Common.SOCKET_CHARSET));
} catch (IOException e) {
e.printStackTrace();
}
}
break;
case MSG_START_SERVER:
Log.d(TAG, "MSG_START_SERVER: ");
startThread();
break;
case MSG_STOP_SERVER:
Log.d(TAG, "MSG_STOP_SERVER: ");
stopThread();
break;
}
return false;
}
public void init() {
Log.d(TAG, "init: ");
mHandlerThread = new HandlerThread(TAG);
mHandlerThread.start();
mHandler = new Handler(mHandlerThread.getLooper(), this);
mSocketServer = new SocketServer();
}
public void start() {
Log.d(TAG, "start ");
mHandler.sendEmptyMessage(MSG_START_SERVER);
}
public void stop() {
Log.d(TAG, "stop: ");
mHandler.sendEmptyMessage(MSG_STOP_SERVER);
}
private void startThread(){
Log.d(TAG, "startThread: ");
mReceiveThread = new ReceiveThread(mSocketServer, this);
mReceiveThread.setName("ReceiveThread");
// mReceiveThread.start();
mServerThread = new ServerThread(mSocketServer, this);
mServerThread.setName("ServerThread");
mServerThread.start();
}
private void stopThread(){
Log.d(TAG, "stopThread: ");
if (null != mReceiveThread) {
mReceiveThread.stopRunning();
try {
mReceiveThread.interrupt();
mReceiveThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
mReceiveThread = null;
}
if (null != mServerThread) {
mServerThread.stopRunning();
try {
mServerThread.interrupt();
mServerThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
mServerThread = null;
}
if (null != mSocketServer) {
mSocketServer.closeSocket();
}
}
public void release() {
Log.d(TAG, "release: ");
mServerThread.stopRunning();
if (null != mHandler) {
mHandler.removeCallbacksAndMessages(null);
}
if (null != mHandlerThread) {
mHandlerThread.quitSafely();
}
mSocketServer.closeSocket();
mIMessageCallback = null;
}
/**
* send message to socket
*
* @param text
*/
public void sendMessage(String text) {
Message message = mHandler.obtainMessage();
message.what = MSG_SEND_DATA;
message.obj = text;
mHandler.sendMessage(message);
}
/**
* set IMessageCallback listener
*
* @param listener
*/
public void setIMessageCallback(IMessageCallback listener) {
mIMessageCallback = listener;
}
public void setPort(int port) {
if (null != mSocketServer) {
mSocketServer.setPort(port);
}
}
public void setIP(String ip) {
if (null != mSocketServer) {
mSocketServer.setIp(ip);
}
}
}