Android 用socket实现通信,连续对话

server端代码:

public static void main(String[] args) { String address = ""; try { InetAddress ip4 = Inet4Address.getLocalHost(); address = ip4.getHostAddress(); System.out.println("本机地址:" + address); } catch (Exception e) { System.out.println("本机地址:" + e.getMessage()); } Scanner s = new Scanner(System.in); int port = s.nextInt(); s.close(); try { ExecutorService service = Executors.newFixedThreadPool(100); ServerSocket ss = new ServerSocket(port); System.out.println("服务器启动成功"+Thread.activeCount()); while (true) { try { service.submit(new SKRunnable(ss.accept())); } catch (Exception e) { System.out.println("服务器异常关闭"+e.getMessage()); break; } } ss.close(); System.out.println("服务器已关闭"); }catch (Exception e) { System.out.println("服务器启动失败:" + e.getMessage()); } }

public class SKRunnable implements Runnable { public static final String encode = "GB18030"; public SKRunnable(Socket socket) { this.socket = socket; } private Socket socket; private DataInputStream dataInputStream; private DataOutputStream dataOutputStream; private Thread readThread; private String client = ""; @Override public void run() { try { client = socket.getInetAddress().getHostAddress() + ":" + socket.getPort(); dataInputStream = new DataInputStream(socket.getInputStream()); dataOutputStream = new DataOutputStream(socket.getOutputStream()); push("连接到服务器成功"); readThread = new Thread() { @Override public void run() { while (true) { try { byte b = dataInputStream.readByte(); int len = dataInputStream.readInt(); byte[] data = new byte[len - 5]; dataInputStream.readFully(data); String receiverStr = new String(data, encode); String sysoStr = "【客户端" + client + "】\n发来内容:" + receiverStr + "\n长度:" + len + ",类型:" + b; System.out.println(sysoStr); long current = System.currentTimeMillis(); if(current % 2 ==0) { push("让我想想该怎么回你......"); sleep(1500); } push(getResponse(current)); } catch (Exception e) { System.out.println("与客户端【" + client + "】断开连接:" + e.getMessage()); System.gc(); break; } } } }; readThread.start(); } catch (Exception e) { System.out.println(Thread.activeCount() + "连接失败2" + e.getMessage()); } } private void push(String content) { try { int type = 1; byte[] data = content.getBytes(encode); int len = data.length + 5; dataOutputStream.writeByte(type); dataOutputStream.writeInt(len); dataOutputStream.write(data); dataOutputStream.flush(); System.out.println("To Client【"+client+"】:"+content); } catch (Exception e) { System.out.println("push:" + e.getMessage()); } } private String getResponse(long cuurent) { String code = String.valueOf(cuurent); code = code.substring(code.length() - 1); int index = MyUtils.toInt(code); switch (index) { case 0: code = "你在干什么?"; break; case 1: code = "你无不无聊?"; break; case 2: code = "你看你一天天的"; break; case 3: code = "你就不能正经点?"; break; case 4: code = "你好意思吗"; break; case 5: code = "快点闭嘴,什么都别说了"; break; case 6: code = "你好漂亮,好好看"; break; case 7: code = "今天天气不错哈"; break; case 8: code = "我要准备爆炸了,你快走!!!"; break; case 9: code = "你以为你是谁?"; break; default: code = "我们懵逼了"; break; } return code; } }

app端代码:

package com.lkl.linc.socketapp.server;import android.text.TextUtils;import com.lkl.linc.socketapp.utils.LG;import java.io.DataInputStream;import java.io.DataOutputStream;import java.net.Socket;import java.util.ArrayList;import java.util.List;public class SKUtils { private static SKUtils i; public static SKUtils get() { if (i == null) { synchronized (SKUtils.class) { if (i == null) { i = new SKUtils(); } } } return i; } private List listListener = new ArrayList<>(); private Socket socket; private DataInputStream dataInputStream; private DataOutputStream dataOutputStream; private Thread readThread; public void startConn() { new Thread() { @Override public void run() { disConn(); try { sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } try { socket = new Socket(ServerUtils.ip(), ServerUtils.port()); socket.setKeepAlive(true); dataInputStream = new DataInputStream(socket.getInputStream()); dataOutputStream = new DataOutputStream(socket.getOutputStream()); readThread = new Thread() { @Override public void run() { while (true) { try { byte b = dataInputStream.readByte(); int len = dataInputStream.readInt(); byte[] data = new byte[len - 5]; dataInputStream.readFully(data); String receiverStr = new String(data, SKSet.encode); if (!TextUtils.isEmpty(receiverStr)) { callBackResult(receiverStr); } LG.i("服务器消息:类型" + b + ",长度:" + len + ",内容:" + receiverStr); } catch (Exception e) { callBackError("服务器服务器断开连接"); readThread = null; dataReset(); LG.e("readThread:" + e.getMessage()); break; } } } }; readThread.start(); callBackResult("服务器连接成功"); } catch (Exception e) { callBackError("服务器连接失败2" + e.getMessage()); LG.e("startConn:" + e.getMessage()); } } }.start(); } public void sendMsg(String content, SKSet.OnSKListener listener) { new Thread() { @Override public void run() { try { if (push(content)) { listener.onResult("发送成功"); } else { listener.onFailed("发送失败"); } } catch (Exception e) { listener.onFailed("发送失败" + e.getMessage()); LG.e("sendMsg:" + e.getMessage()); } } }.start(); } private boolean push(String content) { try { int type = 1; byte[] data = content.getBytes(SKSet.encode); int len = data.length + 5; dataOutputStream.writeByte(type); dataOutputStream.writeInt(len); dataOutputStream.write(data); dataOutputStream.flush(); return true; } catch (Exception e) { System.out.println("push:" + e.getMessage()); return false; } } private void dataReset() { if (socket != null) { socket = null; } if (dataInputStream != null) { dataInputStream = null; } if (dataOutputStream != null) { dataOutputStream = null; } } public void disConn() { new Thread() { @Override public void run() { try { if (socket != null) { try { dataInputStream.close(); dataOutputStream.close(); } catch (Exception e) { LG.e("Stream:" + e.getMessage()); } try { if (!socket.isClosed()) { socket.close(); socket.shutdownOutput(); } } catch (Exception e) { LG.e("socket:" + e.getMessage()); } dataReset(); System.gc(); callBackResult("断开成功"); } } catch (Exception e) { LG.e(e.getMessage()); callBackError("断开失败," + e.getMessage()); } } }.start(); } private void callBackResult(String str) { for (SKSet.OnSKListener l : listListener) { try { l.onResult(str); } catch (Exception e) { LG.e(e.getMessage()); } } } private void callBackError(String error) { for (SKSet.OnSKListener l : listListener) { try { l.onFailed(error); } catch (Exception e) { LG.e(e.getMessage()); } } } public void addListener(SKSet.OnSKListener listener) { if (!listListener.contains(listener)) { listListener.add(listener); } } public void removeListener(SKSet.OnSKListener listener) { listListener.remove(listener); }}

这是只是临时记录下来的代码,基本上没怎么优化。不喜勿喷。

你可能感兴趣的:(Android 用socket实现通信,连续对话)