上个周五的下午,在公司闲来无事,
写了个小程序玩玩,
稍微测试了一下,居然能用!
但由于代码量较少,也谈不上什么设计,
发上来算是个备忘吧:
服务器端程序:
客户端程序:
使用说明:
1.先运行服务器端程序,设定好端口号
2.点击Start按钮,运行服务器
3.运行客户端程序
4.设定好昵称
5.设定与服务器端匹配的端口号和服务器的ip地址
6.点击Login按钮,登录到聊天系统
7.可以聊天了。
写了个小程序玩玩,
稍微测试了一下,居然能用!
但由于代码量较少,也谈不上什么设计,
发上来算是个备忘吧:
服务器端程序:
- package com.test.talk;
- 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.io.DataInputStream;
- import java.io.DataOutputStream;
- import java.io.IOException;
- import java.net.BindException;
- import java.net.ServerSocket;
- import java.net.Socket;
- import java.util.LinkedList;
- import java.util.List;
- import javax.swing.JButton;
- import javax.swing.JFrame;
- import javax.swing.JLabel;
- import javax.swing.JPanel;
- import javax.swing.JTextField;
- public class Server extends JFrame
- {
- boolean started = false;
- private ServerSocket ss = null;
- private List clientList = new LinkedList();
- private JLabel portLbl = null;
- private JTextField portTxt = null;
- private JButton portSetBtn = null;
- private String port = null;
- private JButton startBtn = null;
- private JButton stopBtn = null;
- private JPanel mainPanle = null;
- private JPanel headPanle = null;
- public static void main(String[] args)
- {
- new Server();
- }
- public Server()
- {
- headPanle = new JPanel(new FlowLayout(FlowLayout.LEFT));
- portLbl = new JLabel("PORT");
- portTxt = new JTextField(7);
- portSetBtn = new JButton("OK");
- portSetBtn.addActionListener(new ActionListener()
- {
- public void actionPerformed(ActionEvent e)
- {
- if (portTxt.getText().matches("//d+"))
- {
- port = portTxt.getText();
- startBtn.setEnabled(true);
- stopBtn.setEnabled(true);
- }
- else
- {
- javax.swing.JOptionPane.showMessageDialog(null, "port be inputted is illegal");
- }
- }
- });
- headPanle.add(portLbl);
- headPanle.add(portTxt);
- headPanle.add(portSetBtn);
- getContentPane().add(headPanle, BorderLayout.NORTH);
- startBtn = new JButton("Start");
- stopBtn = new JButton("Stop");
- startBtn.setEnabled(false);
- stopBtn.setEnabled(false);
- mainPanle = new JPanel(new FlowLayout(FlowLayout.CENTER));
- startBtn.addActionListener(new StartClickListener());
- stopBtn.addActionListener(new ActionListener()
- {
- public void actionPerformed(ActionEvent e)
- {
- started = false;
- clientList.clear();
- try
- {
- if (ss != null)
- {
- ss.close();
- }
- }
- catch(IOException e1)
- {
- e1.printStackTrace();
- }
- }
- });
- mainPanle.add(startBtn);
- mainPanle.add(stopBtn);
- getContentPane().add(mainPanle, BorderLayout.CENTER);
- addWindowListener(new WindowAdapter()
- {
- public void windowClosing(WindowEvent e)
- {
- started = false;
- clientList.clear();
- try
- {
- if (ss != null)
- {
- ss.close();
- }
- }
- catch(IOException e1)
- {
- e1.printStackTrace();
- }
- System.exit(0);
- }
- });
- this.setSize(300, 300);
- setLocation(100, 100);
- pack();
- setVisible(true);
- }
- private void start()
- {
- try
- {
- ss = new ServerSocket(Integer.parseInt(port));
- started = true;
- }
- catch(BindException be)
- {
- javax.swing.JOptionPane.showMessageDialog(null, "port is useing by others");
- }
- catch(IOException e)
- {
- javax.swing.JOptionPane.showMessageDialog(null, "connect server fail");
- }
- try
- {
- while(started)
- {
- Socket s = ss.accept();
- ClientImpl cr = new ClientImpl(s);
- new Thread(cr).start();
- clientList.add(cr);
- System.out.println("System Info:" + s.getInetAddress() + "connect successfully");
- }
- }
- catch(IOException e)
- {
- System.out.println("Client closed!");
- }
- }
- class ClientImpl implements Runnable
- {
- private Socket s;
- private DataInputStream dis = null;
- private DataOutputStream dos = null;
- boolean bConnect = false;
- public ClientImpl(Socket s)
- {
- this.s = s;
- try
- {
- dis = new DataInputStream(s.getInputStream());
- dos = new DataOutputStream(s.getOutputStream());
- bConnect = true;
- }
- catch(IOException e)
- {
- e.printStackTrace();
- }
- }
- private void send(String str)
- {
- try
- {
- dos.writeUTF(str);
- }
- catch(IOException e)
- {
- e.printStackTrace();
- }
- }
- public void run()
- {
- ClientImpl cr = null;
- try
- {
- while(bConnect)
- {
- String str = dis.readUTF();
- System.out.println(str);
- for(int i = 0; i < clientList.size(); i++)
- {
- cr = (ClientImpl) clientList.get(i);
- cr.send(str);
- }
- }
- }
- catch(Exception e)
- {
- clientList.remove(cr);
- System.out.println(s.getInetAddress() + "has leaved");
- }
- finally
- {
- try
- {
- if (dis != null)
- dis.close();
- if (dos != null)
- dos.close();
- if (s != null)
- {
- s.close();
- s = null;
- }
- }
- catch(IOException io)
- {
- io.printStackTrace();
- }
- }
- }
- }
- class StartClickListener implements Runnable, ActionListener
- {
- public void actionPerformed(ActionEvent e)
- {
- new Thread(this).start();
- }
- public void run()
- {
- start();
- }
- }
- }
- package com.test.talk;
- 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.io.DataInputStream;
- import java.io.DataOutputStream;
- import java.io.IOException;
- import java.net.Socket;
- import java.net.UnknownHostException;
- import javax.swing.JButton;
- import javax.swing.JFrame;
- import javax.swing.JLabel;
- import javax.swing.JPanel;
- import javax.swing.JTextArea;
- import javax.swing.JTextField;
- /**
- * Client
- *
- * @author hx0272
- *
- */
- public class Client
- {
- public static void main(String[] args)
- {
- ClientFrame frame = new ClientFrame();
- }
- }
- class ClientFrame extends JFrame
- {
- private JPanel mainPanel;
- private JPanel headPanel;
- private JPanel footPanel;
- private JTextArea showArea;
- private JTextField inputTxt;
- private JLabel portLbl;
- private JLabel ipLbl;
- private JLabel nameLbl;
- private JTextField portTxt;
- private JTextField ipTxt;
- private JTextField nameTxt;
- private JButton submitBtn;
- private JButton nameBtn;
- private JButton loginBtn;
- private Socket clientSocket = null;
- private DataOutputStream dos = null;
- private DataInputStream dis = null;
- private boolean bConnect = false;
- private String name = "";
- public ClientFrame()
- {
- init();
- }
- private void init()
- {
- //main panel Begin
- mainPanel = new JPanel();
- showArea = new JTextArea(15, 80);
- showArea.setEditable(false);
- mainPanel.add(showArea);
- getContentPane().add(mainPanel, BorderLayout.CENTER);
- //main panel End
- //head panel Begin
- headPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
- portLbl = new JLabel("PORT");
- portTxt = new JTextField(7);
- ipLbl = new JLabel("IP");
- ipTxt = new JTextField(25);
- nameLbl = new JLabel("name");
- nameTxt = new JTextField(15);
- nameBtn = new JButton("OK");
- loginBtn = new JButton("login");
- nameBtn.addActionListener(new ActionListener()
- {
- public void actionPerformed(ActionEvent e)
- {
- String tmp = nameTxt.getText();
- if (tmp != null || !tmp.equals(""))
- {
- int id = javax.swing.JOptionPane.showConfirmDialog(null, "yes or no", "choose yes",
- javax.swing.JOptionPane.OK_OPTION);
- if (id == 0)
- {
- name = nameTxt.getText();
- loginBtn.setEnabled(true);
- nameBtn.setEnabled(false);
- }
- }
- }
- });
- headPanel.add(portLbl);
- headPanel.add(portTxt);
- headPanel.add(ipLbl);
- headPanel.add(ipTxt);
- headPanel.add(loginBtn);
- headPanel.add(nameLbl);
- headPanel.add(nameTxt);
- headPanel.add(nameBtn);
- loginBtn.setEnabled(false);
- loginBtn.addActionListener(new ButtonClickAction());
- getContentPane().add(headPanel, BorderLayout.NORTH);
- //head panel End
- //foot panel Begin
- footPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
- inputTxt = new JTextField(70);
- submitBtn = new JButton("submit");
- footPanel.add(inputTxt);
- footPanel.add(submitBtn);
- submitBtn.addActionListener(new ButtonClickAction());
- submitBtn.setEnabled(false);
- getContentPane().add(footPanel, BorderLayout.SOUTH);
- //foot panel End
- addWindowListener(new WindowAdapter()
- {
- public void windowClosing(WindowEvent e)
- {
- disConnect();
- System.exit(0);
- }
- });
- this.setSize(300, 300);
- setLocation(100, 100);
- pack();
- setVisible(true);
- }
- /**
- * login button / submit button action listener
- *
- * @author hx0272
- *
- */
- class ButtonClickAction implements ActionListener
- {
- public void actionPerformed(ActionEvent e)
- {
- if ("submit".equals(e.getActionCommand()))
- {
- String str = inputTxt.getText().trim();
- inputTxt.setText("");
- sendToServer(str);
- }
- else if ("login".equals(e.getActionCommand()))
- {
- connect();
- }
- }
- }
- /**
- * enter be inputted event
- *
- * @author hx0272
- */
- class EnterClickAction implements ActionListener
- {
- public void actionPerformed(ActionEvent e)
- {
- String str = inputTxt.getText().trim();
- inputTxt.setText("");
- sendToServer(str);
- }
- }
- /**
- * send message to server
- *
- * @author hx0272
- */
- private void sendToServer(String str)
- {
- try
- {
- dos.writeUTF(name + ":" + str);
- dos.flush();
- }
- catch(IOException e)
- {
- e.printStackTrace();
- }
- }
- /**
- * close resource
- *
- * @author hx0272
- */
- private void disConnect()
- {
- try
- {
- // clientSocket.close();
- //
- // dos.close();
- bConnect = false;
- }
- catch(Exception e)
- {
- e.printStackTrace();
- }
- }
- /**
- * receive message from server
- *
- * @author hx0272
- */
- private class Receive implements Runnable
- {
- public void run()
- {
- try
- {
- while(bConnect)
- {
- String str = dis.readUTF();
- showArea.setText(showArea.getText() + str + '/n');
- }
- }
- catch(IOException e)
- {
- javax.swing.JOptionPane.showMessageDialog(null, "connect server error");
- }
- }
- }
- /**
- * connection begin
- *
- * @author hx0272
- */
- private void connect()
- {
- try
- {
- if (ipTxt.getText().matches("//d{1,3}.//d{1,3}.//d{1,3}.//d{1,3}") && portTxt.getText().matches("//d+"))
- {
- clientSocket = new Socket(ipTxt.getText(), Integer.parseInt(portTxt.getText()));
- dos = new DataOutputStream(clientSocket.getOutputStream());
- dis = new DataInputStream(clientSocket.getInputStream());
- bConnect = true;
- new Thread(new Receive()).start();
- System.out.println("I am coming");
- javax.swing.JOptionPane.showMessageDialog(null, "connect server success");
- submitBtn.setEnabled(true);
- inputTxt.addActionListener(new EnterClickAction());
- }
- else
- {
- javax.swing.JOptionPane.showMessageDialog(null, "port or ip be inputted is illegal");
- }
- }
- catch(UnknownHostException uhe)
- {
- javax.swing.JOptionPane.showMessageDialog(null, "connect server error");
- }
- catch(IOException e)
- {
- javax.swing.JOptionPane.showMessageDialog(null, "connect server error");
- }
- }
- }
1.先运行服务器端程序,设定好端口号
2.点击Start按钮,运行服务器
3.运行客户端程序
4.设定好昵称
5.设定与服务器端匹配的端口号和服务器的ip地址
6.点击Login按钮,登录到聊天系统
7.可以聊天了。