Android Socket 聊天室

项目地址:https://github.com/SunnyLine/ChatRoom.git
切换“test”分支,运行old_server,安装app到手机上
在这里插入图片描述
部分截图:
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述

以下为代码逻辑部分
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();
        }
    }
}

  • 1
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android JSP Socket 聊天是一种基于Android平台和JSP服务器的实时聊天应用程序。Android作为客户端,通过Socket与JSP服务器建立连接,实现用户之间的实时聊天。以下是关于如何实现该聊天的方法: 1. 客户端开发:首先,在Android应用中建立Socket连接。使用Socket类可以实现与服务器的通信。通过建立输入流和输出流,可以实现信息的发送和接收。在聊天中,你可以为每个用户分配一个唯一的Socket连接来进行通信。 2. 服务器端开发:在JSP服务器中,通过接收客户端的Socket连接来进行通信。服务器可以创建一个线程池用于接收客户端的连接请求,并对每个连接进行处理,以便实现多用户的实时聊天功能。 3. 实现实时聊天:在聊天中,当一个用户发送消息时,通过Socket将消息发送到服务器,服务器再将消息广播给其他在线用户,实现实时聊天。在这个过程中,可以使用线程来处理客户端和服务器的连接,以及消息的发送和接收。 4. 用户控制:在聊天中,你还可以实现一些用户控制功能,如用户注册、登录、退出等。可以在用户加入聊天时记录用户信息,并在用户退出时清除相关信息。 综上所述,Android JSP Socket 聊天是一种基于Android平台和JSP服务器的实时聊天应用程序。通过Socket连接,用户可以实现实时聊天,并且可以实现一些用户控制功能。这种聊天可以用于不同的场景,如在线交流、团队协作等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值