Java实现通过服务器实现客户端之间的简单群聊

来源:互联网 发布:linux 查看压缩包类型 编辑:程序博客网 时间:2024/06/03 14:36

描述:

使用了socket编程。主要是通过服务器监听端口,对于新访问的客户端建立一个socket长连接。每次客户端输入信息,先传到服务器,再由服务发给在线的客户端。

其功能模型如下:


运行截图:

1、需要先启动服务器端,界面如下:

2、启动2或2个以上个客户端(名字随机):

3、聊天结果:


代码部分:

服务器端代码实现:

package pack2;import java.net.*;import java.util.ArrayList;import java.util.List;import java.awt.Container;import java.io.*;import javax.swing.JFrame;import javax.swing.JScrollPane;import javax.swing.JTextArea;public class chatServer extends JFrame{/** *  */private static final long serialVersionUID = -4929211394401993088L;static JTextArea textArea;List<Socket> socketList;ServerSocket serverSocket;Socket socket = null;public chatServer()throws IOException{this.setTitle("Server");init();        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        this.setLayout(null);              this.setBounds(0, 0, 300, 510);        this.setResizable(false);        this.setLocation(710,200);        this.setVisible(true);        System.out.println("Sever started!!!");        serverSocket = new ServerSocket(2345);        socketList  = new ArrayList<Socket>();        socket = null;        while (true) {socket = serverSocket.accept();System.out.println("Clinet connected to the server!");socketList.add(socket);new listening(socket, socketList).start();}        }void init(){Container con = this.getContentPane();textArea=new JTextArea();textArea.setBounds(5, 5, 285,440);textArea.setEditable(false);con.add(textArea);JScrollPane scrollPane = new JScrollPane(textArea);scrollPane.setBorder(null);scrollPane.setBounds(5, 5, 285,440);con.add(scrollPane);}public static void  main(String[] args) throws IOException{new chatServer();}}class listening extends Thread{private Socket socket;private List<Socket> socketList;public listening(Socket socket, List<Socket> socketList) {this.socket = socket;this.socketList = socketList;}    @Override    public void run() {    DataInputStream in;    DataOutputStream out;    try {    in=new DataInputStream(socket.getInputStream());    String news;    while(true){    news = in.readUTF();    chatServer.textArea.append(news+"\n");    for(int i=0;i<socketList.size();i++){    out=new DataOutputStream(socketList.get(i).getOutputStream());    out.writeUTF(news);      out.flush();    }    }} catch (IOException e) {// TODO: handle exception}    }}

客户端代码实现:

package pack2;import java.net.*;import java.awt.Container;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyAdapter;import java.awt.event.KeyEvent;import java.io.*;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JScrollPane;import javax.swing.JTextArea;import javax.swing.JTextField;public class chatClient extends JFrame implements Runnable,ActionListener{/** *  */private static final long serialVersionUID = -7103711638195532808L;DataInputStream in;DataOutputStream out;Socket socket;String name,ipAdress;JTextField textField;JTextArea textArea;JButton button;public chatClient(String name){this.name=name;//this.ipAdress=ipAdress;this.setTitle("我是 "+name);init();        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        this.setLayout(null);              this.setBounds(0, 0, 300, 510);        this.setResizable(false);        this.setLocation(400, 200);        this.setVisible(true);        try {        socket=new Socket(this.ipAdress,2345);    in=new DataInputStream(socket.getInputStream());    out=new DataOutputStream(socket.getOutputStream());} catch (IOException e) {}}@Overridepublic void run() {try{         while(true){    textArea.append(in.readUTF()+"\n");         }    }catch(Exception e){}}void init(){Container con = this.getContentPane();button=new JButton("Send");button.setBounds(225,450,65,20);button.addActionListener(this);con.add(button);textField=new JTextField();textField.setBounds(5,450,215,20);textField.addKeyListener(new KeyAdapter() {      public void keyPressed(KeyEvent e) {             if(e.getKeyCode()==KeyEvent.VK_ENTER){        try {out.writeUTF(textField.getText());textField.setText("");} catch (IOException e2) {}        }              }    });con.add(textField);textArea=new JTextArea();textArea.setBounds(5, 5, 285,440);textArea.setEditable(false);JScrollPane scrollPane = new JScrollPane(textArea);scrollPane.setBorder(null);scrollPane.setBounds(5, 5, 285,440);con.add(scrollPane);}@Overridepublic void actionPerformed(ActionEvent e) {if(e.getSource()==button)try {out.writeUTF(this.name+": "+textField.getText());textField.setText("");} catch (IOException e2) {}}public static void main(String[] args) {String []name = {"刘一","陈二","张三","李四","王五","赵六","孙七","周八","吴九","郑十"};java.util.Random random=new java.util.Random();int result=random.nextInt(10);new Thread(new chatClient(name[result])).start();}}





阅读全文
0 0