Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize multi-person chat room with Java Socket

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

这篇文章主要介绍"Java Socket怎么实现多人聊天室",在日常操作中,相信很多人在Java Socket怎么实现多人聊天室问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答"Java Socket怎么实现多人聊天室"的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

Socket可以实现网络上两个程序通过双向通道进行数据的交换,此外它是Java中网络TCP/IP协议的封装,例如可以进行网络通信等等,下面我们就来简单写一下多人聊天室。

首先来分析一下要实现的流程

首先建立一个服务器端,构建ServerSocket并绑定端口

创建socket客户端,连接到指定ip以及其端口

然后使用accept阻塞接收socket发出的连接请求

获取连接后的socket客户端的输入流和输出流

根据输入流和输出流进行两者数据的通信

值得一提是:该Socket是同步阻塞的,因此在socket客户端需要进行创建一个线程,来分别进行向服务器输出,和接收服务器传输的数据。要解决同步阻塞这个问题可以去了解JAVA NIO。

Socket客户端代码如下:import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.net.Socket; public class Client{ public static void main(String[] args) throws IOException { //创建连接指定Ip和端口的socket Socket socket = new Socket("127.0.0.1",5200); //获取系统标准输入流 BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(socket.getOutputStream()); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); //创建一个线程用于读取服务器的信息 new Thread(new Runnable() { @Override public void run() { try { while (true){ System.out.println(in.readLine()); } } catch (IOException e) { e.printStackTrace(); } } }).start(); //写信息给客户端 String line = reader.readLine(); while (!"end".equalsIgnoreCase(line)){ //将从键盘获取的信息给到服务器 out.println(line); out.flush(); //显示输入的信息 line = reader.readLine(); } out.close(); in.close(); socket.close(); }}

由于要接收多个客户端的请求,因此服务端需要多个线程进行分别来接收客户端的请求。

Socket服务端代码如下:import java.io.IOException;import java.net.ServerSocket;import java.net.Socket;import java.util.List;import java.util.Vector; public class Servers { //将接收到的socket变成一个集合 protected static List sockets = new Vector(); public static void main(String[] args) throws IOException { //创建服务端 ServerSocket server = new ServerSocket(5200); boolean flag = true; //接受客户端请求 while (flag){ try { //阻塞等待客户端的连接 Socket accept = server.accept(); synchronized (sockets){ sockets.add(accept); } //多个服务器线程进行对客户端的响应 Thread thread = new Thread(new ServerThead(accept)); thread.start(); //捕获异常。 }catch (Exception e){ flag = false; e.printStackTrace(); } } //关闭服务器 server.close(); } }Server线程代码如下:import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.net.Socket; /** * 服务器线程,主要来处理多个客户端的请求 */public class ServerThead extends Servers implements Runnable{ Socket socket; String socketName; public ServerThead(Socket socket){ this.socket = socket; } @Override public void run() { try { BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); //设置该客户端的端点地址 socketName = socket.getRemoteSocketAddress().toString(); System.out.println("Client@"+socketName+"已加入聊天"); print("Client@"+socketName+"已加入聊天"); boolean flag = true; while (flag) { //阻塞,等待该客户端的输出流 String line = reader.readLine(); //若客户端退出,则退出连接。 if (line == null){ flag = false; continue; } String msg = "Client@"+socketName+":"+line; System.out.println(msg); //向在线客户端输出信息 print(msg); } closeConnect(); } catch (IOException e) { try { closeConnect(); } catch (IOException e1) { e1.printStackTrace(); } } } /** * 向所有在线客户端socket转发消息 * @param msg * @throws IOException */ private void print(String msg) throws IOException { PrintWriter out = null; synchronized (sockets){ for (Socket sc : sockets){ out = new PrintWriter(sc.getOutputStream()); out.println(msg); out.flush(); } } } /** * 关闭该socket的连接 * @throws IOException */ public void closeConnect() throws IOException { System.out.println("Client@"+socketName+"已退出聊天"); print("Client@"+socketName+"已退出聊天"); //移除没连接上的客户端 synchronized (sockets){ sockets.remove(socket); } socket.close(); }}

由于要接收多个客户端的信息,并转发到每一个已经连接上的客户端,因此创建了一个Vector集合来保存每一个客户端Socket,由于是多个线程同时对这个Vector集合进行操作,因此加上synchronized关键字保证同步安全。

先运行服务器端,然后在运行多个客户端就可以进行多人聊天了。

到此,关于"Java Socket怎么实现多人聊天室"的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注网站,小编会继续努力为大家带来更多实用的文章!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report