Android Socket 聊天室

项目地址:https://github.com/SunnyLine/Android-Socket-ChatRoom
部分截图:
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述

以下为代码逻辑部分
Java: 监听某个端口,有用户访问时,将这个Socket放入到一个集合中作为一个用户组,并监听这个Socket的消息。收到任意一个Socket的消息后,再将此消息分发给用户组的每一个成员。
Android:使用Socket连接指定IP指定端口,连接成功后发送一条信息给服务器,服务器会将之转发给其他人,其他人就可以知道组内有新用户加入的信息。离开此页面时也要发送给服务器一条离开的信息,服务器会告知其他用户。在子线程中监听服务器发送的数据进行显示。

Java代码如下:

public class Main {

    private static final int PORT = 9999;
    private static List<Socket> mList = new ArrayList<Socket>();
    private static ServerSocket server = null;
    private static ExecutorService mExecutorService = null; //thread pool

    public static void main(String[] args) {
        try {
            server = new ServerSocket(PORT);
            mExecutorService = Executors.newCachedThreadPool();  //create a thread pool
            System.out.println("服务器已启动...");
            Socket client = null;
            while(true) {
                client = server.accept();
              //把客户端放入客户端集合中
                mList.add(client);
                mExecutorService.execute(new Service(client)); //start a new thread to handle the connection
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
    static class Service implements Runnable {
            private Socket socket;
            private BufferedReader in = null;
            private String msg = "";

            public Service(Socket socket) {
                this.socket = socket;
                try {
                    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                  //客户端只要一连到服务器,便向客户端发送下面的信息。
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

            public byte[] readStream(InputStream inStream) throws Exception {  
                ByteArrayOutputStream outSteam = new ByteArrayOutputStream();  
                byte[] buffer = new byte[1024];  
                int len = -1;  
                while ((len = inStream.read(buffer)) != -1) {  
                    outSteam.write(buffer, 0, len);  
                }  
                outSteam.close();  
                inStream.close();  
                return outSteam.toByteArray();  
            } 

            @Override
            public void run() {
                try {
                    while(true) {
                        if((msg = in.readLine())!= null) {
                            System.out.println("接收:"+msg);
                            ChatBean bean =  new Gson().fromJson(msg, ChatBean.class);
                            //当客户端发送的信息为:exit时,关闭连接
                            if(bean.content.equals("exit")) {
                                System.out.println("用戶:"+bean.name+"已退出谈论组");
                                mList.remove(socket);
                                in.close();
                                socket.close();
                                this.sendmsg();
                                break;
                              //接收客户端发过来的信息msg,然后发送给客户端。
                            } else {
                                this.sendmsg();
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            /**
             * 循环遍历客户端集合,给每个客户端都发送信息。
             * 可以使用观察者模式设计讨论组
             */
           public void sendmsg() {
               System.out.println(msg);
               int num =mList.size();
               for (int index = 0; index < num; index ++) {
                   Socket mSocket = mList.get(index);
                   PrintWriter pout = null;
                   try {
                       pout = new PrintWriter(new BufferedWriter(
                               new OutputStreamWriter(mSocket.getOutputStream())),true);
                       pout.println(msg);
                   }catch (IOException e) {
                       e.printStackTrace();
                   }
               }
           }
        }    

}

Android 部分代码如下:

public interface ChatView {

    public String getHost();
    public String getProt();
    public String getUserId();
    public void showDiaolg(String msg);
    public void receiveMsg(ChatBean bean);
}

public class SocketThread extends Thread {

    private Socket socket = null;
    private BufferedReader in = null;
    private PrintWriter out = null;

    private ChatView chatView;

    public SocketThread(ChatView chatView) {
        this.chatView = chatView;
    }

    private void init() {
        try {
            socket = new Socket(chatView.getHost(), Integer.parseInt(chatView.getProt()));
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
            if (!socket.isOutputShutdown()) {
                ChatBean bean = new ChatBean("join", chatView.getUserId());
                out.println(new Gson().toJson(bean));
            }
        } catch (UnknownHostException e1) {
            e1.printStackTrace();
            mHandler.sendEmptyMessage(-1);
        } catch (IOException ex) {
            ex.printStackTrace();
            mHandler.sendEmptyMessage(0);
        } catch (IllegalArgumentException e2) {
            e2.printStackTrace();
            mHandler.sendEmptyMessage(-2);
        }
    }

    public void sendMsg(String msg) {
        ChatBean bean = new ChatBean(msg, chatView.getUserId());
        if (!TextUtils.isEmpty(msg) && socket != null && socket.isConnected()) {
            if (!socket.isOutputShutdown()) {
                out.println(new Gson().toJson(bean));
            }
        }
    }

    //接收线程发送过来信息,并用TextView显示
    public Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case -2:
                    chatView.showDiaolg("IllegalArgumentException");
                    break;
                case -1:
                    chatView.showDiaolg("UnknownHostException");
                    break;
                case 0:
                    chatView.showDiaolg("IOException");
                    break;
                case 1:
                    String content = (String) msg.obj;
                    ChatBean bean = new Gson().fromJson(content, ChatBean.class);
                    chatView.receiveMsg(bean);
                    break;
            }
        }
    };

    @Override
    public void run() {
        super.run();
        init();
        //接收服务器的信息
        try {
            while (true) {
                if (!socket.isClosed()) {
                    if (socket.isConnected()) {
                        if (!socket.isInputShutdown()) {
                            String content;
                            if ((content = in.readLine()) != null) {
                                content += "\n";
                                Message message = mHandler.obtainMessage();
                                message.obj = content;
                                message.what = 1;
                                mHandler.sendMessage(message);
                            } else {

                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/hello_12413/article/details/51170455