Android Socket简单聊天室的服务端
2014-10-14 18:07:00 3 举报
Android Socket简单聊天室的服务端是一个基于Java的网络通信应用程序,它使用TCP/IP协议实现客户端和服务器之间的数据传输。服务端主要负责监听客户端的连接请求,接收客户端发送的消息并将其广播给所有已连接的客户端,同时将其他客户端发送的消息转发给对应的客户端。服务端采用多线程技术,为每个客户端连接创建一个线程,从而实现并发处理。此外,服务端还具备异常处理、日志记录等功能,以确保程序的稳定性和可维护性。通过搭建这个简单的聊天室服务端,用户可以在Android设备上轻松实现实时聊天功能。
作者其他创作
大纲/内容
Socket聊天室服务端的编写
首先我们要判断下服务端该做什么事情!
public class Server { private static final int PORT = 9999; private List mList = new ArrayList(); private ServerSocket server = null; private ExecutorService mExecutorService = null; //thread pool public static void main(String[] args) { new Server(); } public Server() { try { server = new ServerSocket(PORT); //实例化线程池对象 mExecutorService = Executors.newCachedThreadPool(); System.out.print(\"Server Start ...\\"); Socket client = null; while(true) { client = server.accept(); mList.add(client); //调用线程的execute创建一个用于通信的新线程 mExecutorService.execute(new Service(client)); } }catch (Exception e) { e.printStackTrace(); } } 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())); msg = \"User \" +this.socket.getInetAddress() + \"~Join in!\" +\"The online user:\" +mList.size(); this.sendmsg(); } catch (IOException e) { e.printStackTrace(); } } @Override public void run() { // TODO Auto-generated method stub try { while(true) { if((msg = in.readLine())!= null) { if(msg.equals(\"exit\")) { System.out.println(\"ssssssss\"); mList.remove(socket); in.close(); msg = \"User:\" + socket.getInetAddress() + \"Exit:\" +\"The online user:\"+mList.size(); socket.close(); this.sendmsg(); break; } else { msg = socket.getInetAddress() + \"say:\\t\
0 条评论
下一页