一、创建服务端
/**
* 一、开启线程来通信
* 二、监听端口
* 三、接收消息
* 四、消息处理方法
*/
public class TCPService extends Service {
private static final String TAG = "TCPService";
private String[] serviceMessage = new String[]{"我是1号消息", "我是2号消息", "我是3号消息"};//返回信息
private boolean mIsServiceDestroy = false;
@Override
public void onCreate() {
super.onCreate();
new Thread(new TcpCludeServe()).start();//一
}
public TCPService() {
}
private class TcpCludeServe implements Runnable{
@Override
public void run() {
ServerSocket serverSocket = null;
try {
//监听本地端口
serverSocket = new ServerSocket(8688);//二
}catch (Exception e) {
e.printStackTrace();
}
while (!mIsServiceDestroy) {//如果没有销毁 三
try {
//接收客户端消息
final Socket client = serverSocket.accept();
new Thread() {
@Override
public void run() {
try {
responseClient(client);//接收客户端请求的方法 四
}catch (Exception e){
e.printStackTrace();
}
}
}.start();
}catch (Exception e){
e.printStackTrace();
}
}
}
}
/**
* 接收客户端请求的方法(发送、接收)
* @param client
* @throws IOException
*/
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("欢迎来到聊天室");//这里的out是上边的out
while (!mIsServiceDestroy) {
String str = in.readLine();
Log.d(TAG, "responseClient: mst from client " + str);
if (str == null) {
break;
}
//随机发送消息
int i = new Random().nextInt(serviceMessage.length);
String msg = serviceMessage[i];
out.println(msg);
Log.d(TAG, "sent: " + msg);
}
//关闭流
MyUtils.close(out);//自己写的关闭的方法
MyUtils.close(in);
client.close();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
mIsServiceDestroy = true;
super.onDestroy();
}
}
二、客户端
/**在客户端
* 一、连接服务端,并加入重连机制
* 二、接收信息,其实重点就是处理消息的方法
* 三、退出时关闭Socket
*/
public class MainActivity extends Activity implements View.OnClickListener {
private static final int MESSAGE_RECEIVE_NEW_MSG = 1;
private static final int MESSAGE_SOCKET_CONNECTED = 2;
private PrintWriter mPrintWriter;
private Socket mClientSocket;
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case MESSAGE_RECEIVE_NEW_MSG: {
//动作一
break;
}
case MESSAGE_SOCKET_CONNECTED: {
//动作二
break;
}
default:
break;
}
super.handleMessage(msg);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化TextView等组件
//启动service
Intent service = new Intent(this, TCPService.class);
startService(service);
new Thread() {//连接服务器并处理消息 耗时操作要新开个进程
@Override
public void run() {
connectTCPServer();//连接服务器的方法(连接和处理消息)
super.run();
}
}.start();
}
@Override
protected void onDestroy() {
if (mClientSocket != null) {
try{
mClientSocket.shutdownInput();
mClientSocket.close();
}catch (Exception e) {
e.printStackTrace();
}
}
super.onDestroy();
}
@Override
public void onClick(View v) {//忽略
if (v == mSendButton) {
//这个按钮是用来获取当前时间的
}
}
private void connectTCPServer() {
/**
* 连接端口
*/
Socket socket = null;
while (socket == null) {
try {
socket = new Socket("localhost", 8688);
mClientSocket = socket; //用于销毁时的判断
mPrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
mHandler.sendEmptyMessage(MESSAGE_SOCKET_CONNECTED);//发送连接
System.out.println("connect ok");
}catch (Exception e ) {
SystemClock.sleep(1000);
e.printStackTrace();
}
}
/**
* 消息处理
*/
try{
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (!MainActivity.this.isFinishing()) {
String msg = br.readLine();
System.out.println("receive" + msg);
if (msg != null) { //如果有消息
//处理消息
}
}
//退出
System.out.println("quit");
MyUtil.close(mPrintWriter);
MyUtil.close(br);
socket.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}