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

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;ServerUI extends JFrame { main(String[] args) {ServerUI serverUI = new ServerUI();}JButton btSend;JTextField tfSend;JTextArea taShow;Server server;List<Socket> clients; 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);}},免备案空间命运如同手中的掌纹,无论多曲折,终掌握在自己手中。

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

相关文章:

你感兴趣的文章:

标签云: