Java实现简单局域网聊天室

时间:2021-12-28 03:56:06

本文实例为大家分享了Java实现简单局域网聊天室的具体代码,供大家参考,具体内容如下

Java 的Socket编程:

1、TCP协议是面向连接的、可靠的、有序的、以字节流的方式发送数据,通过三次握手方式建立连接,形成传输数据的通道,在连接中进行大量数据的传输,效率会稍低

2、Java中基于TCP协议实现网络通信的类

  • 客户端的Socket类
  • 服务器端的ServerSocket类

Java实现简单局域网聊天室

3、Socket通信的步骤

① 创建ServerSocket和Socket

② 打开连接到Socket的输入/输出流

③ 按照协议对Socket进行读/写操作

④ 关闭输入输出流、关闭Socket

4、服务器端:

① 创建ServerSocket对象,绑定监听端口

② 通过accept()方法监听客户端请求

③ 连接建立后,通过输入流读取客户端发送的请求信息

④ 通过输出流向客户端发送乡音信息

⑤ 关闭相关资源

5、客户端:

① 创建Socket对象,指明需要连接的服务器的地址和端口号

② 连接建立后,通过输出流想服务器端发送请求信息

③ 通过输入流获取服务器响应的信息

④ 关闭响应资源

实现的聊天室例子:

实现的效果是如下:

Java实现简单局域网聊天室

服务端代码:

  1. package socket.server;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.PrintWriter;
  6. import java.net.ServerSocket;
  7. import java.net.Socket;
  8. import java.util.ArrayList;
  9.  
  10. /**
  11. * @author 超
  12. * Create by fengc on 2018/7/25 21:21
  13. */
  14. public class Server extends Thread{
  15.  
  16. ServerUI ui;
  17. ServerSocket ss;
  18. BufferedReader reader;
  19. PrintWriter writer;
  20.  
  21. public Server(ServerUI ui) {
  22. this.ui = ui;
  23. this.start();
  24. }
  25.  
  26. @Override
  27. public void run() {
  28. try {
  29. ss = new ServerSocket(8081);
  30. ui.clients=new ArrayList<>();
  31. println("启动服务器成功:端口8081");
  32. while (true) {
  33. println("等待客户端链接.......................................");
  34. Socket client = ss.accept();
  35. ui.clients.add(client);
  36. println("连接成功,客户端请求服务端的详细信息:" + client.toString());
  37. new ListenerClient(ui, client);
  38. }
  39. } catch (IOException e) {
  40. println("启动服务器失败:端口8081");
  41. println(e.toString());
  42. e.printStackTrace();
  43. }
  44.  
  45. }
  46.  
  47. public synchronized void sendMsg(String msg) {
  48. try {
  49. for (int i = 0; i < ui.clients.size(); i++) {
  50. Socket client = ui.clients.get(i);
  51. writer = new PrintWriter(client.getOutputStream(), true);
  52. writer.println(msg);
  53. }
  54. } catch (Exception e) {
  55. println(e.toString());
  56. }
  57. }
  58.  
  59. public void println(String s) {
  60. if (s != null) {
  61. s = "服务端打印消息:" + s;
  62. this.ui.taShow.setText(this.ui.taShow.getText() + s + "\n");
  63. System.out.println(s + "\n");
  64. }
  65. }
  66.  
  67. public void closeServer() {
  68. try {
  69. if (ss != null)
  70. ss.close();
  71. if (reader != null)
  72. reader.close();
  73. if (writer != null)
  74. writer.close();
  75. } catch (IOException e) {
  76. // TODO Auto-generated catch block
  77. e.printStackTrace();
  78. }
  79.  
  80. }
  81.  
  82. }
  1. package socket.server;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStreamReader;
  6. import java.io.PrintWriter;
  7. import java.net.Socket;
  8.  
  9. /**
  10. * @author 超
  11. * Create by fengc on 2018/7/25 21:33
  12. * 这个类是服务器端的等待客户端发送信息*
  13. */
  14. public class ListenerClient extends Thread{
  15.  
  16. BufferedReader reader;
  17. PrintWriter writer;
  18. ServerUI ui;
  19. Socket client;
  20.  
  21. public ListenerClient(ServerUI ui, Socket client) {
  22. this.ui = ui;
  23. this.client=client;
  24. this.start();
  25. }
  26.  
  27. //为每一个客户端创建线程等待接收信息,然后把信息广播出去
  28. @Override
  29. public void run() {
  30. String msg = "";
  31. while (true) {
  32. try {
  33. reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
  34. writer = new PrintWriter(client.getOutputStream(), true);
  35. msg = reader.readLine();
  36. sendMsg(msg);
  37. } catch (IOException e) {
  38. println(e.toString());
  39. break;
  40. }
  41. if (msg != null && msg.trim() != "") {
  42. println("客户端 " + msg);
  43. }
  44. }
  45. }
  46.  
  47. //把信息广播到所有用户
  48. public synchronized void sendMsg(String msg) {
  49. try {
  50. for (int i = 0; i < ui.clients.size(); i++) {
  51. Socket client = ui.clients.get(i);
  52. writer = new PrintWriter(client.getOutputStream(), true);
  53. writer.println(msg);
  54. }
  55.  
  56. } catch (Exception e) {
  57. println(e.toString());
  58. }
  59. }
  60.  
  61. public void println(String s) {
  62. if (s != null) {
  63. this.ui.taShow.setText(this.ui.taShow.getText() + s + "\n");
  64. System.out.println(s + "\n");
  65. }
  66. }
  67. }
  1. package socket.server;
  2.  
  3. import javax.swing.*;
  4. import java.awt.*;
  5. import java.awt.event.ActionEvent;
  6. import java.awt.event.ActionListener;
  7. import java.awt.event.WindowAdapter;
  8. import java.awt.event.WindowEvent;
  9. import java.net.Socket;
  10. import java.util.List;
  11.  
  12. /**
  13. * @author 超
  14. * Create by fengc on 2018/7/25 21:21
  15. */
  16. public class ServerUI extends JFrame {
  17.  
  18. public static void main(String[] args) {
  19. new ServerUI();
  20. }
  21.  
  22. public JButton btStart;//启动服务器
  23. public JButton btSend;//发送信息按钮
  24. public JTextField tfSend;//需要发送的文本信息
  25.  
  26. public JTextArea taShow;//信息展示
  27. public Server server;//用来监听客户端连接
  28. static List<Socket> clients;//保存连接到服务器的客户端
  29.  
  30. public ServerUI() {
  31. super("服务器端");
  32. btStart = new JButton("启动服务");
  33. btSend = new JButton("发送信息");
  34. tfSend = new JTextField(10); //装在输入文字
  35. taShow = new JTextArea();
  36. //点击按钮,所做的是事情,启动服务器
  37. btStart.addActionListener(new ActionListener() {
  38. public void actionPerformed(ActionEvent e) {
  39. server = new Server(ServerUI.this);
  40. }
  41. });
  42. //点击发送消息按钮
  43. btSend.addActionListener(new ActionListener() {
  44. public void actionPerformed(ActionEvent e) {
  45. server.sendMsg(tfSend.getText());
  46. tfSend.setText("");
  47. }
  48. });
  49. //初始化界面
  50. this.addWindowListener(new WindowAdapter() {
  51. //关闭按钮点击事件
  52. public void windowClosing(WindowEvent e) {
  53. int a = JOptionPane.showConfirmDialog(null, "确定关闭吗?", "温馨提示",
  54. JOptionPane.YES_NO_OPTION);
  55. if (a == 1) {
  56. server.closeServer();
  57. System.exit(0); // 关闭
  58. }
  59. }
  60. });
  61. //底部启动服务按钮与发送消息按钮
  62. JPanel top = new JPanel(new FlowLayout());
  63. top.add(tfSend);
  64. top.add(btSend);
  65. top.add(btStart);
  66. this.add(top, BorderLayout.SOUTH);
  67. //中部显示消息栏 信息展示
  68. final JScrollPane sp = new JScrollPane();
  69. sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
  70. sp.setViewportView(this.taShow);
  71. this.taShow.setEditable(false);
  72. this.add(sp, BorderLayout.CENTER);
  73. this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  74. this.setSize(400, 300);
  75. this.setLocation(100, 200);
  76. this.setVisible(true);
  77. }
  78.  
  79. }

客户端代码:

  1. package socket.clinet;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStreamReader;
  6. import java.io.PrintWriter;
  7. import java.net.Socket;
  8.  
  9. /**
  10. * @author 超
  11. * Create by fengc on 2018/7/25 21:41
  12. */
  13. public class Client extends Thread {
  14.  
  15. ClientUI ui;
  16. Socket client;
  17. BufferedReader reader;
  18. PrintWriter writer;
  19.  
  20. public Client(ClientUI ui) {
  21. this.ui = ui;
  22. try {
  23. String ip = ui.tfIP.getText(); //得到输入的ip地址
  24. int port = Integer.parseInt(ui.tfPort.getText()); //得到输入的端口
  25. client = new Socket(ip, port);//这里设置连接服务器端的IP的端口
  26. println("连接服务器成功,服务器端口地址:" + port);
  27. reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
  28. writer = new PrintWriter(client.getOutputStream(), true);
  29. String name = ui.tfName.getText();
  30. if (name == null || "".equals(name)) {
  31. name = "匿名者";
  32. }
  33. sendMsg("会员 " + name + ",登录上来了........................");
  34. // 如果为 true,则 println、printf 或 format 方法将刷新输出缓冲区
  35. } catch (NumberFormatException nu) {
  36. println("端口请输入正确.......");
  37. nu.printStackTrace();
  38. } catch (IOException e) {
  39. println("连接服务器失败:请输入正确的IP地址与端口");
  40. println(e.toString());
  41. e.printStackTrace();
  42. }
  43. this.start();
  44. }
  45.  
  46. public void run() {
  47. String msg = "";
  48. while (true) {
  49. try {
  50. msg = reader.readLine();
  51. } catch (IOException e) {
  52. println("服务器断开连接");
  53.  
  54. break;
  55. }
  56. if (msg != null && msg.trim() != "") {
  57. println(msg);
  58. }
  59. }
  60. }
  61.  
  62. public void sendMsg(String msg) {
  63. try {
  64. writer.println(msg);
  65. } catch (Exception e) {
  66. println(e.toString());
  67. }
  68. }
  69.  
  70. public void println(String s) {
  71. if (s != null) {
  72. this.ui.taShow.setText(this.ui.taShow.getText() + s + "\n");
  73. System.out.println(s + "\n");
  74. }
  75. }
  76.  
  77. }
  1. package socket.clinet;
  2.  
  3. import javax.swing.*;
  4. import java.awt.*;
  5. import java.awt.event.ActionEvent;
  6. import java.awt.event.ActionListener;
  7. import java.awt.event.WindowAdapter;
  8. import java.awt.event.WindowEvent;
  9.  
  10. /**
  11. * @author 超
  12. * Create by fengc on 2018/7/25 21:40
  13. */
  14. public class ClientUI extends JFrame {
  15.  
  16. public static void main(String[] args) {
  17. new ClientUI();
  18. }
  19.  
  20. public JButton btStart;
  21. public JButton btSend;
  22. public JTextField tfSend; //装在输入文字
  23. public JTextPane nameText; //输入名字
  24. public JTextPane ipTex; //输入名字
  25. public JTextPane portText; //输入名字
  26. public JTextField tfName; //服务器ip
  27. public JTextField tfIP; //服务器ip
  28. public JTextField tfPort; //服务器端口
  29. public JTextArea taShow;
  30. public Client server;
  31.  
  32. public ClientUI() {
  33. super("客户端");
  34. btStart = new JButton("启动连接");
  35. btSend = new JButton("发送信息");
  36. tfSend = new JTextField(20);
  37. tfIP = new JTextField(8);
  38. tfPort = new JTextField(3);
  39. tfName = new JTextField(6);
  40. nameText = new JTextPane();nameText.setText("登录名");nameText.setEditable(false);
  41. ipTex = new JTextPane();ipTex.setText("服务地址");ipTex.setEditable(false);
  42. portText = new JTextPane();portText.setText("服务端口");portText.setEditable(false);
  43. taShow = new JTextArea();
  44. //启动链接按钮事件
  45. btStart.addActionListener(new ActionListener() {
  46. public void actionPerformed(ActionEvent e) {
  47. server = new Client(ClientUI.this);
  48. }
  49. });
  50. //发送按钮事件
  51. btSend.addActionListener(new ActionListener() {
  52. public void actionPerformed(ActionEvent e) {
  53. String name = tfName.getText();
  54. if (name == null || "".equals(name)) {
  55. name = "匿名者";
  56. }
  57. server.sendMsg(name + ":" + tfSend.getText());
  58. tfSend.setText("");
  59. }
  60. });
  61.  
  62. this.addWindowListener(new WindowAdapter() {
  63. public void windowClosing(WindowEvent e) {
  64. int a = JOptionPane.showConfirmDialog(null, "确定关闭吗?", "温馨提示",
  65. JOptionPane.YES_NO_OPTION);
  66. if (a == 1) {
  67. System.exit(0); // 关闭
  68. }
  69. }
  70. });
  71. //底部的发送信息框与链接按钮
  72. JPanel top = new JPanel(new FlowLayout());
  73. top.add(tfSend); //发送文本
  74. top.add(btSend); //发送按钮
  75. this.add(top, BorderLayout.SOUTH); //加载到底部
  76.  
  77. //头部放连接服务的
  78. JPanel northJpannel = new JPanel(new FlowLayout());
  79. northJpannel.add(nameText);
  80. northJpannel.add(tfName);
  81. northJpannel.add(ipTex);
  82. northJpannel.add(tfIP);
  83. northJpannel.add(portText);
  84. northJpannel.add(tfPort);
  85. northJpannel.add(btStart);
  86. this.add(northJpannel,BorderLayout.NORTH); //加载到头部
  87.  
  88. final JScrollPane sp = new JScrollPane();
  89. sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
  90. sp.setViewportView(this.taShow);
  91. this.taShow.setEditable(false);
  92. this.add(sp, BorderLayout.CENTER);
  93. this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  94. this.setSize(500, 400);
  95. this.setLocation(600, 200);
  96. this.setVisible(true);
  97. }
  98.  
  99. }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

原文链接:https://blog.csdn.net/yundanfengqingfeng/article/details/81212632