java socket聊天小demo

來源:互聯網
上載者:User

最近需要學習下socket,就順帶做了個聊天的小demo。

基本是抄人家的,我加了個util類,最佳化了下。

有swing介面的,學生和初學者可以拿走學習下。

http://download.csdn.net/detail/sysmaid/3880649

貼部分代碼。

伺服器端 線程:

/** * 服務線程類 * @author JingHui * * create by 2011-11-24 下午1:38:10 */class ServerThread extends Thread {private Socket socket;public ServerThread(Socket socket){this.socket = socket;}public void run(){try{ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());while(true){Vector v = null;try{v = (Vector)ois.readObject();}catch(Exception e){e.printStackTrace();System.out.println("=======與用戶端通訊出現錯誤=======");}if(v!=null && v.size()>0){for(int i=0; i<v.size(); i++){String info = (String)v.get(i);String key = "";if(info.startsWith(ChatUtil.MSG_LOGIN)){key = info.substring(7);//獲得使用者名稱map.put(key, socket);//用戶端添加至列表ta_info.append(key + " login...\n");Set<String> set = map.keySet();Iterator<String> it = set.iterator();while(it.hasNext()){//迭代map,向所有用戶端發送登入資訊String reciveKey = it.next();//表示接收資訊的key,即使用者名稱Socket s = map.get(reciveKey);PrintWriter pw = new PrintWriter(s.getOutputStream(), true);pw.println(info);pw.flush();}}else if(info.startsWith(ChatUtil.MSG_EXIT)){//使用者退出key = info.substring(6);//獲得退出使用者的keyois.close();socket.close();map.remove(key);Set<String> set = map.keySet();Iterator<String> it = set.iterator();while(it.hasNext()){String reciveKey = it.next();Socket s = map.get(reciveKey);PrintWriter pw = new PrintWriter(s.getOutputStream(), true);pw.println(info);pw.flush();}ta_info.append(key + " exit...\n");return;//退出線程}else if(info.startsWith(ChatUtil.MSG_USERLIST)){//傳遞當前線上使用者列表String userList = "";Set<String> set = map.keySet();Iterator<String> it = set.iterator();while(it.hasNext()){key = it.next();userList += key + ",";}key = info.substring(10);Iterator<String> it2 = set.iterator();while(it2.hasNext()){String reciveKey = it2.next();if(key.equals(reciveKey)){Socket s = map.get(reciveKey);PrintWriter pw = new PrintWriter(s.getOutputStream(), true);pw.println(ChatUtil.MSG_USERLIST + userList);pw.flush();}}}else{//正常的訊息轉寄String[] infos = ChatUtil.formatInfos(info);Set<String> set = map.keySet();Iterator<String> it = set.iterator();while(it.hasNext()){String reciveKey = it.next();if(reciveKey.equals(infos[1])){//尋找到接受者Socket s = map.get(reciveKey);PrintWriter pw = new PrintWriter(s.getOutputStream(), true);pw.println(info);//原文轉寄,用戶端進行處理pw.flush();}}}//end else}//end for}//end if v}//end while}catch(Exception e){e.printStackTrace();ta_info.append(socket + "退出異常。\n");}}}//end class ServerThread

用戶端介面:

/** * 建構函式 * 在構造中初始化介面 */public ChatClientFrame(){super();this.setTitle("小兔聊天室用戶端");this.setBounds(100, 100, 385, 288);final JPanel panel = new JPanel();this.getContentPane().add(panel, BorderLayout.SOUTH);final JLabel label = new JLabel();label.setText("輸入聊天內容");panel.add(label);tf_send = new JTextField();tf_send.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent arg0) {send();//調用發送方法}});tf_send.setPreferredSize(new Dimension(180, 25));panel.add(tf_send);//發送訊息地區final JButton button = new JButton();button.setText("發   送");button.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){send();}});panel.add(button);//添加發送按鈕final JSplitPane splitPane = new JSplitPane();splitPane.setDividerLocation(100);//分隔條的位置this.getContentPane().add(splitPane, BorderLayout.CENTER);final JScrollPane scrollPane = new JScrollPane();splitPane.setRightComponent(scrollPane);ta_info = new JTextArea();ta_info.setFont(new Font("", Font.BOLD, 14));scrollPane.setViewportView(ta_info);//資訊顯示地區//-------顯示使用者列表 start-------final JScrollPane scrollPane1 = new JScrollPane();userList = new JList();userList.setModel(new DefaultComboBoxModel(new String[] {""}));scrollPane1.setViewportView(userList);splitPane.setLeftComponent(scrollPane1);//-------顯示使用者列表 end-------//-------顯示使用者登入 start-------final JPanel panel_1 = new JPanel();final JLabel label_1 = new JLabel();label_1.setText("使用者名稱稱:");panel_1.add(label_1);tf_newUser = new JTextField();tf_newUser.setPreferredSize(new Dimension(140, 25));panel_1.add(tf_newUser);final JButton button_1 = new JButton();button_1.setText("登   錄");button_1.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent arg0) {//進行登入操作if(loginFlag){JOptionPane.showConfirmDialog(null, "目前使用者已登入");return;}String userName = tf_newUser.getText().trim();Vector<String> v = new Vector<String>();v.add(ChatUtil.fittingLoginMsg(userName));//發送登入資訊try{out.writeObject(v);//發送out.flush();}catch(Exception e){e.printStackTrace();}tf_newUser.setEnabled(false);//使用者名稱不可修改button_1.setVisible(false);//登入按鈕隱藏loginFlag = true;getOnlineUser(userName);//擷取線上使用者列表}});panel_1.add(button_1);final JButton button_2 = new JButton();button_2.setText("退   出");button_2.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent arg0) {if(!loginFlag){//未登入JOptionPane.showMessageDialog(null, "已退出或未登入!");return;}String exitUser = tf_newUser.getText().trim();Vector<String> v = new Vector<String>();v.add(ChatUtil.fittingExitMsg(exitUser));//退出資訊try{out.writeObject(v);out.flush();}catch(Exception e){e.printStackTrace();}System.exit(0);}});panel_1.add(button_2);this.getContentPane().add(panel_1, BorderLayout.NORTH);//-------顯示使用者登入 end-------//-------系統托盤 start-------if(SystemTray.isSupported()){URL url = ChatClientFrame.class.getResource(ChatUtil.LOGO_IMAGE);ImageIcon i_con= new ImageIcon(url);Image image = i_con.getImage();TrayIcon trayIcon = new TrayIcon(image);trayIcon.addMouseListener(new MouseAdapter(){public void mouseClicked(MouseEvent e) {if(e.getClickCount()==2){showFrame();//顯示介面}}});trayIcon.setToolTip("小兔聊天");PopupMenu popupMenu = new PopupMenu();MenuItem exitMenu = new MenuItem("退出");exitMenu.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent arg0) {String exitUser = tf_newUser.getText().trim();Vector<String> v = new Vector<String>();v.add(ChatUtil.fittingExitMsg(exitUser));//退出資訊try{out.writeObject(v);out.flush();out.close();socket.close();}catch(Exception e){e.printStackTrace();}System.exit(0);}});popupMenu.add(exitMenu);trayIcon.setPopupMenu(popupMenu);SystemTray systemTray = SystemTray.getSystemTray();try {systemTray.add(trayIcon);} catch (Exception e1) {e1.printStackTrace();}}//-------系統托盤 end-------}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.