Java实现简单局域网聊天室
作者:yundanfengqingfeng
这篇文章主要为大家详细介绍了Java实现简单局域网聊天室,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文实例为大家分享了Java实现简单局域网聊天室的具体代码,供大家参考,具体内容如下
Java 的Socket编程:
1、TCP协议是面向连接的、可靠的、有序的、以字节流的方式发送数据,通过三次握手方式建立连接,形成传输数据的通道,在连接中进行大量数据的传输,效率会稍低
2、Java中基于TCP协议实现网络通信的类
- 客户端的Socket类
- 服务器端的ServerSocket类
3、Socket通信的步骤
① 创建ServerSocket和Socket
② 打开连接到Socket的输入/输出流
③ 按照协议对Socket进行读/写操作
④ 关闭输入输出流、关闭Socket
4、服务器端:
① 创建ServerSocket对象,绑定监听端口
② 通过accept()方法监听客户端请求
③ 连接建立后,通过输入流读取客户端发送的请求信息
④ 通过输出流向客户端发送乡音信息
⑤ 关闭相关资源
5、客户端:
① 创建Socket对象,指明需要连接的服务器的地址和端口号
② 连接建立后,通过输出流想服务器端发送请求信息
③ 通过输入流获取服务器响应的信息
④ 关闭响应资源
实现的聊天室例子:
实现的效果是如下:
服务端代码:
package socket.server; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; /** * @author 超 * Create by fengc on 2018/7/25 21:21 */ public class Server extends Thread{ ServerUI ui; ServerSocket ss; BufferedReader reader; PrintWriter writer; public Server(ServerUI ui) { this.ui = ui; this.start(); } @Override public void run() { try { ss = new ServerSocket(8081); ui.clients=new ArrayList<>(); println("启动服务器成功:端口8081"); while (true) { println("等待客户端链接......................................."); Socket client = ss.accept(); ui.clients.add(client); println("连接成功,客户端请求服务端的详细信息:" + client.toString()); new ListenerClient(ui, client); } } catch (IOException e) { println("启动服务器失败:端口8081"); println(e.toString()); e.printStackTrace(); } } public synchronized void sendMsg(String msg) { try { for (int i = 0; i < ui.clients.size(); i++) { Socket client = ui.clients.get(i); writer = new PrintWriter(client.getOutputStream(), true); writer.println(msg); } } catch (Exception e) { println(e.toString()); } } public void println(String s) { if (s != null) { s = "服务端打印消息:" + s; this.ui.taShow.setText(this.ui.taShow.getText() + s + "\n"); System.out.println(s + "\n"); } } public void closeServer() { try { if (ss != null) ss.close(); if (reader != null) reader.close(); if (writer != null) writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package socket.server; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; /** * @author 超 * Create by fengc on 2018/7/25 21:33 * 这个类是服务器端的等待客户端发送信息* */ public class ListenerClient extends Thread{ BufferedReader reader; PrintWriter writer; ServerUI ui; Socket client; public ListenerClient(ServerUI ui, Socket client) { this.ui = ui; this.client=client; this.start(); } //为每一个客户端创建线程等待接收信息,然后把信息广播出去 @Override public void run() { String msg = ""; while (true) { try { reader = new BufferedReader(new InputStreamReader(client.getInputStream())); writer = new PrintWriter(client.getOutputStream(), true); msg = reader.readLine(); sendMsg(msg); } catch (IOException e) { println(e.toString()); break; } if (msg != null && msg.trim() != "") { println("客户端 " + msg); } } } //把信息广播到所有用户 public synchronized void sendMsg(String msg) { try { for (int i = 0; i < ui.clients.size(); i++) { Socket client = ui.clients.get(i); writer = new PrintWriter(client.getOutputStream(), true); writer.println(msg); } } catch (Exception e) { println(e.toString()); } } public void println(String s) { if (s != null) { this.ui.taShow.setText(this.ui.taShow.getText() + s + "\n"); System.out.println(s + "\n"); } } }
package socket.server; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.net.Socket; import java.util.List; /** * @author 超 * Create by fengc on 2018/7/25 21:21 */ public class ServerUI extends JFrame { public static void main(String[] args) { new ServerUI(); } public JButton btStart;//启动服务器 public JButton btSend;//发送信息按钮 public JTextField tfSend;//需要发送的文本信息 public JTextArea taShow;//信息展示 public Server server;//用来监听客户端连接 static List<Socket> clients;//保存连接到服务器的客户端 public ServerUI() { super("服务器端"); btStart = new JButton("启动服务"); btSend = new JButton("发送信息"); tfSend = new JTextField(10); //装在输入文字 taShow = new JTextArea(); //点击按钮,所做的是事情,启动服务器 btStart.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { server = new Server(ServerUI.this); } }); //点击发送消息按钮 btSend.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { server.sendMsg(tfSend.getText()); tfSend.setText(""); } }); //初始化界面 this.addWindowListener(new WindowAdapter() { //关闭按钮点击事件 public void windowClosing(WindowEvent e) { int a = JOptionPane.showConfirmDialog(null, "确定关闭吗?", "温馨提示", JOptionPane.YES_NO_OPTION); if (a == 1) { server.closeServer(); System.exit(0); // 关闭 } } }); //底部启动服务按钮与发送消息按钮 JPanel top = new JPanel(new FlowLayout()); top.add(tfSend); top.add(btSend); top.add(btStart); this.add(top, BorderLayout.SOUTH); //中部显示消息栏 信息展示 final JScrollPane sp = new JScrollPane(); sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); sp.setViewportView(this.taShow); this.taShow.setEditable(false); this.add(sp, BorderLayout.CENTER); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setSize(400, 300); this.setLocation(100, 200); this.setVisible(true); } }
客户端代码:
package socket.clinet; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; /** * @author 超 * Create by fengc on 2018/7/25 21:41 */ public class Client extends Thread { ClientUI ui; Socket client; BufferedReader reader; PrintWriter writer; public Client(ClientUI ui) { this.ui = ui; try { String ip = ui.tfIP.getText(); //得到输入的ip地址 int port = Integer.parseInt(ui.tfPort.getText()); //得到输入的端口 client = new Socket(ip, port);//这里设置连接服务器端的IP的端口 println("连接服务器成功,服务器端口地址:" + port); reader = new BufferedReader(new InputStreamReader(client.getInputStream())); writer = new PrintWriter(client.getOutputStream(), true); String name = ui.tfName.getText(); if (name == null || "".equals(name)) { name = "匿名者"; } sendMsg("会员 " + name + ",登录上来了........................"); // 如果为 true,则 println、printf 或 format 方法将刷新输出缓冲区 } catch (NumberFormatException nu) { println("端口请输入正确......."); nu.printStackTrace(); } catch (IOException e) { println("连接服务器失败:请输入正确的IP地址与端口"); println(e.toString()); e.printStackTrace(); } this.start(); } public void run() { String msg = ""; while (true) { try { msg = reader.readLine(); } catch (IOException e) { println("服务器断开连接"); break; } if (msg != null && msg.trim() != "") { println(msg); } } } public void sendMsg(String msg) { try { writer.println(msg); } catch (Exception e) { println(e.toString()); } } public void println(String s) { if (s != null) { this.ui.taShow.setText(this.ui.taShow.getText() + s + "\n"); System.out.println(s + "\n"); } } }
package socket.clinet; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; /** * @author 超 * Create by fengc on 2018/7/25 21:40 */ public class ClientUI extends JFrame { public static void main(String[] args) { new ClientUI(); } public JButton btStart; public JButton btSend; public JTextField tfSend; //装在输入文字 public JTextPane nameText; //输入名字 public JTextPane ipTex; //输入名字 public JTextPane portText; //输入名字 public JTextField tfName; //服务器ip public JTextField tfIP; //服务器ip public JTextField tfPort; //服务器端口 public JTextArea taShow; public Client server; public ClientUI() { super("客户端"); btStart = new JButton("启动连接"); btSend = new JButton("发送信息"); tfSend = new JTextField(20); tfIP = new JTextField(8); tfPort = new JTextField(3); tfName = new JTextField(6); nameText = new JTextPane();nameText.setText("登录名");nameText.setEditable(false); ipTex = new JTextPane();ipTex.setText("服务地址");ipTex.setEditable(false); portText = new JTextPane();portText.setText("服务端口");portText.setEditable(false); taShow = new JTextArea(); //启动链接按钮事件 btStart.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { server = new Client(ClientUI.this); } }); //发送按钮事件 btSend.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String name = tfName.getText(); if (name == null || "".equals(name)) { name = "匿名者"; } server.sendMsg(name + ":" + tfSend.getText()); tfSend.setText(""); } }); this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { int a = JOptionPane.showConfirmDialog(null, "确定关闭吗?", "温馨提示", JOptionPane.YES_NO_OPTION); if (a == 1) { System.exit(0); // 关闭 } } }); //底部的发送信息框与链接按钮 JPanel top = new JPanel(new FlowLayout()); top.add(tfSend); //发送文本 top.add(btSend); //发送按钮 this.add(top, BorderLayout.SOUTH); //加载到底部 //头部放连接服务的 JPanel northJpannel = new JPanel(new FlowLayout()); northJpannel.add(nameText); northJpannel.add(tfName); northJpannel.add(ipTex); northJpannel.add(tfIP); northJpannel.add(portText); northJpannel.add(tfPort); northJpannel.add(btStart); this.add(northJpannel,BorderLayout.NORTH); //加载到头部 final JScrollPane sp = new JScrollPane(); sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); sp.setViewportView(this.taShow); this.taShow.setEditable(false); this.add(sp, BorderLayout.CENTER); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setSize(500, 400); this.setLocation(600, 200); this.setVisible(true); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。