简单的基于换行分隔符进行命令交互的TCP Server。
本代码是利用回车换行进行数据分隔的,适合简单的指令交互,如果要实现复杂的控制,请自己改写相关代码。
package com.kingron.tcpserver;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
class TcpServerThread extends Thread {
static String TAG = "TCP Server";
class SocketData {
Socket socket;
InputStream inputStream;
OutputStream outputStream;
String data;
}
Handler handler = null;
private int port;
private byte buffer[] = new byte[1500];
ServerSocket serverSocket;
public TcpServerThread(Handler handler, int port) {
this.port = port;
this.handler = handler;
}
@Override
public void run() {
super.run();
try {
serverSocket = new ServerSocket(port);
} catch (IOException e) {
Log.e(TAG, "监听端口" + port + "失败: " + e.getMessage());
return;
}
while (true) {
try {
Socket socket = serverSocket.accept();
Log.i(TAG, "客户端连接: " + socket.getInetAddress().getHostAddress() + ":" + socket.getPort());
ReceiveThread receive_Thread = new ReceiveThread();
receive_Thread.client = socket;
receive_Thread.inputStream = socket.getInputStream();
receive_Thread.outputStream = socket.getOutputStream();
receive_Thread.start();
} catch (IOException e) {
Log.d(TAG, "服务器错误: " + e.getMessage());
}
}
}
class ReceiveThread extends Thread
{
public Socket client;
public InputStream inputStream;
public OutputStream outputStream;
public void sendData(String msg) {
if (outputStream != null && client != null && client.isConnected()) {
try {
outputStream.write(msg.getBytes());
} catch (IOException e) {
Log.d(TAG, String.format("发送数据错误: %s:%d, %s", client.getInetAddress().getHostAddress(), client.getPort(), e.getMessage()));
try {
client.close();
} catch (IOException e1) {
}
}
}
}
public void run()
{
BufferedReader br=new BufferedReader(new InputStreamReader(inputStream));
while (true)
try {
final String text = br.readLine();
if (text == null || client.isClosed()) {
Log.d(TAG, String.format("连接断开: %s:%d", client.getInetAddress().getHostAddress(), client.getPort()));
break;
}
Message msg = new Message();
SocketData data = new SocketData();
data.data = text;
data.inputStream = inputStream;
data.outputStream = outputStream;
data.socket = client;
msg.obj = data;
handler.sendMessage(msg);
} catch (Exception e) {
Log.d(TAG, String.format("客户端错误,断开连接: %s:%d, %s", client.getInetAddress().getHostAddress(), client.getPort(), e.getMessage()));
return;
}
}
}
}