Java 仿QQ聊天源代码(一)

2014-11-24 09:10:14 · 作者: · 浏览: 3

Java 仿QQ聊天源代码介绍,本源码实现了群聊和私聊。


截图如下:



代码文件清单如下:


Client.java、ClientThread.java、Server.java、ServerThread.java共四个java文件


因为本人的能力有限,如果你觉得那里有不合理的地方可以给我留言或者q我


下面是Client.java代码内容:


package cc;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Inet4Address;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;

public class Client extends JFrame implements ActionListener {
private JPanel jp;
private JButton connect, send, exit;
private JTextArea ja;
private Socket socket = null;

public JTextArea getJa() {
return ja;
}

public void setJa(JTextArea ja) {
this.ja = ja;
}

private JTextField juser, jmess;
private JScrollPane jsp;
private JComboBox jcb;

public JComboBox getJcb() {
return jcb;
}

public void setJcb(JComboBox jcb) {
this.jcb = jcb;
}

public Client() {
try {
UIManager
.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
into();
this.setBounds(100, 200, 390, 350);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}

public void into() {
jp = new JPanel();
jp.setLayout(null);
this.add(jp);
juser = new JTextField();
juser.setBounds(60, 15, 150, 20);
jp.add(juser);
connect = new JButton("Connect");
connect.addActionListener(this);
connect.setBounds(220, 15, 80, 20);
jp.add(connect);
ja = new JTextArea();
ja.setLineWrap(true);
ja.setSize(350, 220);
jsp = new JScrollPane(ja, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
jsp.setBounds(20, 40, 340, 220);
jp.add(jsp);
// 添加用于发送信息的文本框
jmess = new JTextField();
jmess.setBounds(15, 275, 130, 20);
jp.add(jmess);
// 添加用户名称的下拉菜单
jcb = new JComboBox();
jcb.addItem("USERS");
jcb.setBounds(152, 275, 80, 20);
jp.add(jcb);
// 添加发送按钮
send = new JButton("发送");
send.setBounds(235, 273, 60, 25);
send.addActionListener(this);
send.setEnabled(false);
jp.add(send);
// 添加推出按钮
exit = new JButton("退出");
exit.setBounds(300, 273, 60, 25);
exit.addActionListener(this);
exit.setEnabled(false);
jp.add(exit);
}

public static void main(String[] args) {
new Client().setVisible(true);
}

@Override
public void actionPerformed(ActionEvent e) {
String name = e.getActionCommand();
if (name.equals("Connect")) {
if (juser.getText().equals("")) {
JOptionPane jop = new JOptionPane();
jop.showMessageDialog(this, "用户名不能为空!!");
System.out.println("用户名为空!!");
} else {
try {
// 获取ip和用户名格式 USERS:iP: