基于socket的网络聊天室java,java socket实现聊天

  基于socket的网络聊天室java,java socket实现聊天

  本文实例为大家分享了爪哇岛套接字实现简易局域网聊天室的具体代码,供大家参考,具体内容如下

  

服务器端

ServerFrame.java

 

  包com。eze。聊天室。服务器;导入Java。awt。事件队列;导入javax。挥棒。jframe导入javax。挥棒。jpanel导入javax。挥棒。边框。空边框;导入javax。挥棒。jlabel导入Java。awt。颜色;导入Java。awt。字体;导入javax。挥棒。jtextfield导入javax。挥棒。jbutton导入javax。挥棒。joptionpane导入javax。挥棒。jtextarea导入javax。挥棒。jscrollpane导入Java。awt。事件。密钥适配器;导入Java。awt。事件。关键事件;导入Java。awt。事件。鼠标适配器;导入Java。awt。事件。鼠标事件;公众的类服务器框架扩展JFrame {/* * * */private static final long serialVersionUID=1L;私有JPanel内容窗格私有JTextField txtPortprivate JLabel lblonlinecount private JTextArea txtAreaInfo私有服务器服务器;私有JTextArea txtAreaPals/** *启动应用程序. public static void main(String[]args){ event queue。invoke later(new Runnable(){ public void run(){ try { server frame frame=new server frame();框架。设置可见(真);} catch(Exception e){ e . printstacktrace();} } });} /** *创建框架. public server frame(){ this。settitle(“服务器”);这个。setresizable(false);setDefaultCloseOperation(JFrame .EXIT _ ON _ CLOSE);setBounds(100,100,658,428);内容窗格=new JPanel();内容窗格。设置前景(颜色.深灰);内容窗格。设置边框(新的空边框(5,5,5,5));setContentPane(内容窗格);内容窗格。设置布局(空);JLabel LBL端口=新JLabel(端口: );lblPort.setFont(新字体(宋体,字体。平原,18));lblPort.setBounds(14,13,72,31);内容窗格。添加(LBL港);txt port=new JTextField();txt端口。addkey listener(new key adapter(){ @ Override public void key typed(key event e){ int c=e . getkey char();如果(!(三)键事件VK_0摄氏度键事件. VK _ 9)){ e .消费();

             }            }        });        txtPort.setFont(new Font("宋体", Font.PLAIN, 20));        txtPort.setBounds(89, 18, 138, 24);        contentPane.add(txtPort);        txtPort.setColumns(10);        JScrollPane scrollPane = new JScrollPane();        scrollPane.setBounds(245, 103, 378, 272);        contentPane.add(scrollPane);        txtAreaInfo = new JTextArea();        scrollPane.setViewportView(txtAreaInfo);        txtAreaInfo.setFont(new Font("Monospaced", Font.PLAIN, 20));        JButton btnChange = new JButton("start");        btnChange.addMouseListener(new MouseAdapter() {            private boolean flag = true;            @Override            public void mouseClicked(MouseEvent e) {                String portStr = txtPort.getText().trim();                boolean isvalid = false;                int port = 9999;                if(!(portStr.startsWith("0") portStr.equals(""))){                    port = Integer.valueOf(portStr);                    if(port >= 1024 && port <= 65535)                        isvalid = true;                }                if(!isvalid){                    JOptionPane.showMessageDialog(ServerFrame.this, "invalid port that is expected to put into the range of 1024~65535");                    return;                }                if(flag){                    btnChange.setText("stop");                    txtAreaInfo.append("server startedn");                    flag = false;                    ServerFrame.this.server = new Server(ServerFrame.this, ServerFrame.this.getTitle(), port);                    Thread thdServer = new Thread(new Runnable() {                        @Override                        public void run() {                            ServerFrame.this.server.start();                        }                    });                    thdServer.start();                }else{                    btnChange.setText("start");                    ServerFrame.this.server.stop();                    txtAreaInfo.append("server stoppedn");                    flag = true;                }            }        });        btnChange.setFont(new Font("宋体", Font.PLAIN, 19));        btnChange.setBackground(new Color(240, 255, 240));        btnChange.setForeground(new Color(178, 34, 34));        btnChange.setBounds(270, 17, 113, 27);        contentPane.add(btnChange);        JLabel lblPalsOnline = new JLabel("pals online:");        lblPalsOnline.setBounds(18, 73, 113, 18);        contentPane.add(lblPalsOnline);        JLabel lblLogInfo = new JLabel("log info");        lblLogInfo.setBounds(285, 73, 72, 18);        contentPane.add(lblLogInfo);        lblOnlineCount = new JLabel("0");        lblOnlineCount.setBounds(123, 75, 72, 18);        contentPane.add(lblOnlineCount);        JScrollPane scrollPane_1 = new JScrollPane();        scrollPane_1.setBounds(14, 111, 213, 264);        contentPane.add(scrollPane_1);        txtAreaPals = new JTextArea();        scrollPane_1.setViewportView(txtAreaPals);    }    public JLabel getLblOnlineCount() {        return lblOnlineCount;    }    public JTextArea getTxtAreaPals() {        return txtAreaPals;    }    public JTextArea getTxtAreaInfo() {        return txtAreaInfo;    }}Server.java

  

package com.eze.chatroom.server;import java.io.IOException;import java.net.ServerSocket;import java.net.Socket;import java.net.SocketException;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import javax.swing.JTextArea;public class Server {    private ServerSocket server;    private List<Socket> clients;    private Map<String, String> pals;    @SuppressWarnings("unused")    private String name;    private int port;    private ServerFrame frame;    public Server(ServerFrame frame, String name, int port){        this.frame = frame;        this.name = name;        this.port = port;        this.clients = new ArrayList<>();        this.pals = new HashMap<>();    }    public void start(){        try {            this.server = new ServerSocket(port);            System.out.println("server start at port "+port);            while(true){                Socket client = server.accept();                Thread thdHandConn = new Thread(new HandleConnection(client, clients, pals, frame));                thdHandConn.start();            }        }catch(SocketException e){            System.out.println("server stop");        }catch (IOException e) {            e.printStackTrace();        }    }    public void stop(){        try {            for(Socket sock : clients){                sock.close();            }            server.close();        } catch (IOException e) {            e.printStackTrace();        }    }    public static void autoRoll(JTextArea area){        area.setCaretPosition(area.getText().length());    }}

HandleConnnection.java

 

  

package com.eze.chatroom.server;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.IOException;import java.net.Socket;import java.net.SocketException;import java.text.SimpleDateFormat;import java.util.Date;import java.util.List;import java.util.Map;public class HandleConnection implements Runnable {    private Socket client;    private List<Socket> clients;    private Map<String, String> pals;    private ServerFrame frame;    public HandleConnection(Socket client, List<Socket> clients, Map<String, String> pals, ServerFrame frame){        this.client = client;        this.clients = clients;        this.pals = pals;        this.frame = frame;    }    @Override    public void run() {        String username = null;        SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");        try {            DataInputStream dataInput = new DataInputStream(client.getInputStream());            DataOutputStream dataOutput = new DataOutputStream(client.getOutputStream());            String totalFirst = dataInput.readUTF();            username = totalFirst.split("_")[0];            if(username.equals("")){                dataOutput.writeUTF("no");                client.close();                return;            }            dataOutput.writeUTF("ok");            String hello = formatDate.format(new Date())+"n"+client.getRemoteSocketAddress().toString()+username+" join rommn";            frame.getTxtAreaInfo().append(hello);            Server.autoRoll(frame.getTxtAreaInfo());            this.forwardMsg(hello);            clients.add(client);            pals.put(client.getRemoteSocketAddress().toString(), username);            this.updatePalsList();            while(true){                String word = dataInput.readUTF();                String date = formatDate.format(new Date());                String msg = date+" "+username+"n"+word;                frame.getTxtAreaInfo().append(msg+"n");                Server.autoRoll(frame.getTxtAreaInfo());                this.forwardMsg(msg);            }        }catch (SocketException e) {            clients.remove(client);            pals.remove(client.getRemoteSocketAddress().toString(), username);            this.updatePalsList();            String leaveMsg = formatDate.format(new Date())+"n"+username+" leaved roomn";            this.frame.getTxtAreaInfo().append(leaveMsg);            Server.autoRoll(frame.getTxtAreaInfo());            this.forwardMsg(leaveMsg);        }catch (IOException e) {            e.printStackTrace();        }    }    protected void updatePalsList(){        this.frame.getLblOnlineCount().setText(String.valueOf(clients.size()));        this.frame.getTxtAreaPals().setText("");        for(Map.Entry<String, String> entry : pals.entrySet()){            this.frame.getTxtAreaPals().append(entry.getKey()+" "+entry.getValue()+"n");        }    }    protected void forwardMsg(String msg){        try {            for(Socket sock : clients){                if(sock != client){                    DataOutputStream dataOutput = new DataOutputStream(sock.getOutputStream());                    dataOutput.writeUTF(msg);                }            }        } catch (IOException e) {            e.printStackTrace();        }    }}

客户端

ClientLoginViewer.java

 

  

package com.eze.chatroom.client;import java.awt.EventQueue;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.border.EmptyBorder;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JTextField;import javax.swing.JButton;import java.awt.Font;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import java.awt.event.KeyAdapter;import java.awt.event.KeyEvent;import java.awt.event.ActionListener;import java.awt.event.ActionEvent;public class ClientLoginViewer extends JFrame {    /**     *      */    private static final long serialVersionUID = 1L;    private JPanel contentPane;    private ClientWin win;    private JTextField txtUsername;    private JTextField txtServer;    private JLabel lblPort;    private JTextField txtPort;    private Client client;    /**     * Launch the application.     */    public static void main(String[] args) {        EventQueue.invokeLater(new Runnable() {            public void run() {                try {                    ClientLoginViewer frame = new ClientLoginViewer();                    frame.setVisible(true);                } catch (Exception e) {                    e.printStackTrace();                }            }        });    }    /**     * Create the frame.     */    public ClientLoginViewer() {        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        setBounds(100, 100, 603, 366);        contentPane = new JPanel();        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));        setContentPane(contentPane);        contentPane.setLayout(null);        JLabel lblNewLabel = new JLabel("username:");        lblNewLabel.setFont(new Font("宋体", Font.PLAIN, 20));        lblNewLabel.setBounds(71, 41, 113, 18);        contentPane.add(lblNewLabel);        txtUsername = new JTextField();        txtUsername.setText("admin");        txtUsername.setBounds(209, 38, 235, 24);        contentPane.add(txtUsername);        txtUsername.setColumns(10)      

	  
	  
	  
	  
	  
	  
        

郑重声明:本文由网友发布,不代表盛行IT的观点,版权归原作者所有,仅为传播更多信息之目的,如有侵权请联系,我们将第一时间修改或删除,多谢。

留言与评论(共有 条评论)
   
验证码: