用J2SE写的QQ聊天室源代码(简单版)客户端

用swing做了简单的界面。可以直接修改IP和端口,进行局域网或者是interent网的聊天。

通用的

代码已经过测试可用

/**客户端

*/

package QQ;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;

import javax.swing.*;

import java.net.*;

public class QQclient {

 public static void main(String[] args) throws Exception {
  final String string = args[0];
  JFrame frame = new JFrame("QQ聊天大厅"+string);
  frame.setSize(500, 500);
  frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
  LayoutManager m = new BorderLayout();
  frame.setLayout(m);
  JPanel panel = new JPanel();
  final JComboBox combobox = new JComboBox();
  combobox.addItem("所有人");
  final JTextField jtf = new JTextField(25);
  JButton jb = new JButton("确定");
  LayoutManager m1 = new FlowLayout();
  panel.setLayout(m1);
  panel.add(combobox);
  panel.add(jtf);
  panel.add(jb);
  final JTextArea jta = new JTextArea();
  jta.setEditable(false); 
  JScrollPane jsp = new JScrollPane(jta);
  frame.add(panel, "South");
  frame.add(jsp);
  final Socket s = new Socket("127.0.0.1", 9000);
  final OutputStream ops = s.getOutputStream();
  final OutputStreamWriter osw = new OutputStreamWriter(ops);
  final BufferedWriter bw = new BufferedWriter(osw);
  bw.write(string + ":name");
  bw.newLine();
  bw.flush();
  frame.setVisible(true);
  class MyActionListener implements ActionListener {
   public void actionPerformed(ActionEvent e) {
    try {
     String s3;
     s3 = (String) combobox.getSelectedItem();
     String s4;
     s4 = jtf.getText();
     bw.write(string + ":" + s3 + ":" + s4);
     bw.newLine();
     bw.flush();
     jtf.setText(" ");
    } catch (IOException e1) {
     e1.printStackTrace();
    }
   }
  }
  MyActionListener mal = new MyActionListener();
  jb.addActionListener(mal);
  jtf.addActionListener(mal);
  InputStream ips = s.getInputStream();
  InputStreamReader isr = new InputStreamReader(ips);
  BufferedReader br = new BufferedReader(isr);
  String s5 = null;
  String str = null;
  while ((s5 = br.readLine()) != null) {
   if (s5.indexOf(":name") != -1) {
    StringTokenizer st = new StringTokenizer(s5, ":");
    str = st.nextToken();
    int a = 0;
    for (int j = 0; j < combobox.getItemCount(); j++) {
     if (str.equals((String) combobox.getItemAt(j))) {
      a = a + 1;
     }
    }
    System.out.println(a);
    if (a == 0) {
     combobox.addItem(str);
     //jta.append(str + " 进来了");
     //jta.append("/n");
    }
   }else if(s5.indexOf(":welcome")!=-1){
    StringTokenizer st = new StringTokenizer(s5, ":");
    str = st.nextToken();
    jta.append("欢迎"+str+"的来到"+"/n");
   
    
   }else if(s5.indexOf(":离开聊天室")!=-1){
    StringTokenizer st = new StringTokenizer(s5, ":");
    str = st.nextToken();
    combobox.removeItem(str);
   }else {
   
    jta.append(s5+"/n"); 
   }
  }
 }

你可能感兴趣的:(exception,qq,String,J2SE,import,聊天)