java网络编程,通过TCP,Socket实现多对一的局域网聊天室

可以实现多个客户端连接服务器,服务器接收到信息就会把信息广播到所有的客户端

这是服务器端的代码

View Code

import java.awt.BorderLayout;
import java.awt.FlowLayout;
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;import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
/*这个类是服务器端的UI*/
public class ServerUI extends JFrame {public static void main(String[] args) {ServerUI serverUI = 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);}
}

View Code

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
/*这个类是服务器端的等待客户端连接*/
public class Server extends Thread {ServerUI ui;ServerSocket ss;BufferedReader reader;PrintWriter writer;public Server(ServerUI ui) {this.ui = ui;this.start();}public void run() {try {ss = new ServerSocket(1228);ui.clients=new ArrayList<Socket>();println("启动服务器成功:端口1228");while (true) {println("等待客户端");Socket client = ss.accept();ui.clients.add(client);println("连接成功" + client.toString());new ListenerClient(ui, client);}} catch (IOException e) {println("启动服务器失败:端口1228");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) {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();}}
}

View Code

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
/*这个类是服务器端的等待客户端发送信息*/
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();}//为每一个客户端创建线程等待接收信息,然后把信息广播出去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());// e.printStackTrace();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");}}
}

客户端代码

View Code

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;public class ClientUI extends JFrame {public static void main(String[] args) {ClientUI client = new ClientUI();}public ClientUI() {super("客户端");btStart = new JButton("启动连接");btSend = new JButton("发送信息");tfSend = new JTextField(10);tfIP = new JTextField(10);tfPost = new JTextField(5);taShow = new JTextArea();btStart.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {server = new ClientThread(ClientUI.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) {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(600, 200);this.setVisible(true);}public     JButton btStart;public     JButton btSend;public     JTextField tfSend;public     JTextField tfIP;public     JTextField tfPost;public     JTextArea taShow;public     ClientThread server;}

View Code

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;public class ClientThread extends Thread {ClientUI ui;Socket client;BufferedReader reader;PrintWriter writer;public ClientThread(ClientUI ui) {this.ui = ui;try {client = new Socket("127.0.0.1", 1228);//这里设置连接服务器端的IP的端口println("连接服务器成功:端口1228");reader = new BufferedReader(new InputStreamReader(client.getInputStream()));writer = new PrintWriter(client.getOutputStream(), true);// 如果为 true,则 println、printf 或 format 方法将刷新输出缓冲区} catch (IOException e) {println("连接服务器失败:端口1228");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");}}}

转载于:https://www.cnblogs.com/taoweiji/archive/2012/12/14/2818801.html

java网络编程,通过TCP,Socket实现多对一的局域网聊天室相关推荐

  1. Java——网络编程(实现基于命令行的多人聊天室)

    2019独角兽企业重金招聘Python工程师标准>>> 目录: 1.ISO和TCP/IP分层模型 2.IP协议 3.TCP/UDP协议 4.基于TCP的网络编程 5.基于UDP的网络 ...

  2. Java网络编程:TCP实现群聊私聊代码

    Java网络编程:TCP实现群聊&私聊代码 和上一篇博客差不多,只不过是在群里的基础之上增加了私聊的功能,我们约定,私聊格式为:@xxx:msg 如何实现私聊呢,加入客户端c给服务器发送消息, ...

  3. 【java网络编程】TCP三次握手、四次挥手,常见Socket通信BIO

    网络编程,网络通信 内容管理 TCP三次握手,四次挥手 TCP 建立连接 --- 三次握手 TCP断开 ---- 四次挥手 java网络IO BIO 同步阻塞 Socket通信模型 BIO网络通信De ...

  4. java 网络编程 聊天_Java——网络编程(实现基于命令行的多人聊天室)

    目录: 1.ISO和TCP/IP分层模型 2.IP协议 3.TCP/UDP协议 4.基于TCP的网络编程 5.基于UDP的网络编程 6.基于TCP的多线程的聊天室的实现 1.ISO和TCP/IP分层模 ...

  5. Java网络编程二:Socket详解

    Socket又称套接字,是连接运行在网络上两个程序间的双向通讯的端点. 一.使用Socket进行网络通信的过程 服务端:服务器程序将一个套接字绑定到一个特定的端口,并通过此套接字等待和监听客户端的连接 ...

  6. Java网络编程:TCP,UDP,sock编程

    第一节 网络基础知识 常用的通信协议 MAC地址:(Media Access Control Address,媒体存取控制位址), IP:(Internet Protocol,网际协议) UDP:(U ...

  7. java 网络编程 UDP TCP

    网络编程 网络编程主要用于解决计算机与计算机(手机.平板..)之间的数据传输问题. 网络编程: 不需要基于html页面就可以达到数据之间的传输. 比如: feiQ , QQ , 微信.... 网页编程 ...

  8. Java网络编程:TCP实现聊天

    客户端 package com.zhl.nett;import java.io.IOException; import java.io.OutputStream; import java.net.In ...

  9. JAVA网络编程:TCP/IP数据包结构

    2019独角兽企业重金招聘Python工程师标准>>> 一般来说,网络编程我们仅仅须要调用一些封装好的函数或者组件就能完毕大部分的工作,可是一些特殊的情况下,就须要深入的理解网络数据 ...

最新文章

  1. 当网站遇到黑链时该如何进行处理?
  2. 优秀好文收录(持续更新...)
  3. Python提取数字图片特征向量
  4. __name__=__main__
  5. android ne调试工具,Android调试工具adb的正确使用方式
  6. python没有代码提示怎么设置_Python Kite 使用教程 轻量级代码提示
  7. [转]Android编程之BitmapFactory.decodeResource加载图片缩小的原因及解决方法
  8. 剑指offer面试题[40]-数组中只出现一次的数字
  9. 如何监控防火墙后的流量?
  10. 3D Max 渲染和渲染农场渲染经常会出现白点?网渲和本地通用解决~
  11. 一网打尽车载以太网之SOMEIP(上)
  12. python 柱状图和折线图放在一起_python中用matplotlib画折线图、柱状图、散点图
  13. 英文科技论文写作与学术报告Lecture1习题答案
  14. easyboot的一个严重不足
  15. 求和 矩阵迹的性质_怎么证明矩阵特征值的和等于矩阵的迹_
  16. 【设计模式】结构型模式之代理模式
  17. 通过canvas给图片添加水印
  18. markdown转VNode
  19. 亥姆霍兹线圈主要用途有哪些
  20. 股票基础知识(入市必读)

热门文章

  1. JZOJ 5244. 【NOIP2017模拟8.8A组】Daydreamin ' (daydream)
  2. db2 replace函数的用法_SQL基础知识:常用字符处理函数
  3. C#接口(Interface)理解
  4. matlab中线型和颜色控制
  5. matlab常用命令参考
  6. R-CNN 《Rich Feature Hierachies for Accurate Object Detection and Semantic Segmentation》论文笔记
  7. python tkinter 背景色改变不了_python – 在Tkinter中动态更改小部件背景颜色
  8. 2020-11-30 离散系统自适应控制中的一个关键性引理及证明
  9. 实验三——vlan间路由
  10. centos 安装mysql