2.客户端关键代码
客户端主要的类:ChatClient类,Main类以及ClientT1类。
ChatClient类负责用户登录界面的创建。
Main类主要负责用户聊天界面的创建。
clientt1由Main创建并启动以完成用户的通信以及文件传输功能。
ChatClient类:
其中主要包括几个类,有:JDBC类(完成数据库查询工作),Find类完成用户密码找回的动作以及Register类完成用户注册工作。
还一个用户合法性检测功能我直接写在Main里面。
ChatClient类我用的是NetBeans开发工具可视化界面编程编写的代码所以完整的不能给出仅仅给出关键代码:
(1)用户合法性检测:
具体代码后面。
Main类
package chat;
import javax.swing.event.*;
import java.io.*;
import java.net.*;
import javax.swing.*;
//
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.*;
public class Main extends JFrame implements ActionListener,ListSelectionListener{
ClientT1 CT;
JDBC jdbc=new JDBC();
set s;
String str;
// JMenuBar jMenuBar = new JMenuBar();
public String receiveFile="E:\\";
// JMenu serviceMenu = new JMenu ("功能");
// JMenuItem ting= new JMenuItem ("听歌");
//JMenuItem game= new JMenuItem ("游戏");
//JMenuItem browse=new JMenuItem ("浏览器");
//JMenuItem =new JMenuItem ("退出(X)");
File sendFile;
boolean t=true;
BorderLayout borderLayout1;
//JComboBox combobox;
JList List;
DefaultListModel Model;
String ip;
int port=8888;
Socket socket;
//ObjectOutputStream output;
//ObjectInputStream input;
DataOutputStream output;
DataInputStream input;
JLabel showstatus;
String mname;
//ChatDialog C1;
Dimension faceSize;
JTextArea da,da2;
JScrollPane memberPane,J,J2;
JPanel toolBar, JMpane, contentPanel,statusPanel,JC ;
JButton Leave,setupButton,Link,helpButton,send,mp3,Quit;
HelpDialog helpDialog;
public static JTextField statusField = new JTextField("欢迎使用QQ聊天工具");
public Main(String name) {
mname=name;
initUI();
//this.setJMenuBar(jMenuBar);
this.setResizable(false);
this.pack();
this.setSize(faceSize);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation( (int) (screenSize.width - faceSize.getWidth()) / 2,
(int) (screenSize.height - faceSize.getHeight()) / 2);
this.setTitle("QQ聊天");
ImageIcon ii = null; ii = new ImageIcon("src\\8.jpg");//C:\\Documents and Settings\\Administrator\\My Documents\\My Pictures\\8.jpg");
Image i = ii.getImage();
this.setIconImage(i);
// this.setUndecorated(true);
this.setVisible(true);
}
public void initUI() {
Font displayFont = new Font("Serif", Font.BOLD, 18);
Model = new DefaultListModel();
Model.addElement("所有人"); //文件列表
List= new JList(Model); List.setName("在线成员");
List.setFont(displayFont);
List.setVisibleRowCount(4);
List.addListSelectionListener(this);
/* jMenuBar.add (serviceMenu);
serviceMenu.add (ting);
serviceMenu.add (browse);
serviceMenu.add (game);
ting.addActionListener(this);
browse.addActionListener(this);
game.addActionListener(this);
//serviceMenu.add (exitItem);*/
Border border = BorderFactory.createBevelBorder(BevelBorder.LOWERED,
new Color(45, 92, 162),
new Color(43, 66, 97),
new Color(45, 92, 162),
new Color(84, 123, 200));
borderLayout1= new BorderLayout();
faceSize= new Dimension(350, 500);
contentPanel = new JPanel();
JPanel statusPanel = new JPanel();
toolBar = new JPanel();
showstatus=new JLabel();
da=new JTextArea("系统信息\n");//da.append("how are you ?\n");
da.setRows(15);
// da.setColumns(20);
da.setLineWrap(true);da.setEditable(false);
da2=new JTextArea("");//da2.append("how are you ?\n");
da2.setRows(6);
//da.setColumns(10);
da2.setLineWrap(true);
JC=new JPanel();JC.setSize(190,50);
J=new JScrollPane(); J.setBorder(border);
J.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
J.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
J.setSize(190,200);J.setBackground(Color.blue);
J.setViewportView(da);
J2=new JScrollPane();
J2.setBorder(border);
J2.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
J2.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
J2.setSize(190,50);J.setBackground(Color.blue);
J2.setViewportView(da2);
Quit=new JButton("退出");Quit.addActionListener(this);
BorderLayout borderLayout = new BorderLayout();
Leave=new JButton("离开");
setupButton = new JButton("设置");
Link=new JButton("连接");
helpButton = new JButton("帮助");
JButton aboutButton = new JButton("功能");
send=new JButton("文件传输");send.setBorder(null);
mp3=new JButton("mp3");mp3.setBorder(null);
mp3.setOpaque(false);mp3.setContentAreaFilled(false);
toolBar.setBorder(border);
toolBar.setPreferredSize(new Dimension(780, 35));
toolBar.setMinimumSize(new Dimension(780, 35));
toolBar.setLayout(new FlowLayout(FlowLayout.LEFT));
send.setOpaque(false);send.setContentAreaFilled(false);
Quit.setOpaque(false);Quit.setContentAreaFilled(false);Quit.setBorder(null);
setupButton.setOpaque(false);setupButton.setContentAreaFilled(false);setupButton.setBorder(null);
Link.setOpaque(false);Link.setContentAreaFilled(false);Link.setBorder(null);
helpButton.setOpaque(false);helpButton.setContentAreaFilled(false);helpButton.setBorder(null);
aboutButton.setOpaque(false);aboutButton.setContentAreaFilled(false);aboutButton.setBorder(null);
Leave.setOpaque(false);Leave.setContentAreaFilled(false);Leave.setBorder(null);
toolBar.add(setupButton); setupButton.addActionListener(this);
toolBar.add(Link); Link.addActionListener(this);
toolBar.add(helpButton); helpButton.addActionListener(this);
toolBar.add(aboutButton); aboutButton.addActionListener(this);
//toolBar.add(Leave);
//Leave.addActionListener(this);
// toolBar.add(serviceMenu);
toolBar.add(send); send.addActionListener(this);
mp3.addActionListener(this);
toolBar.add(mp3);
toolBar.add(Quit);
/*combobox = new JComboBox();
combobox.insertItemAt("所有人",0);
combobox.setSelectedIndex(0);
JPanel JMpane=new JPanel();JMpane.setSize(40,2000);JMpane.setLayout(new GridLayout(2000,1));
JMpane.add(combobox);//combobox.addItem("jasstion");
combobox.addItemListener(this);*/
memberPane= new JScrollPane();
memberPane.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
memberPane.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
memberPane.setSize(190,380);J.setBackground(Color.blue);
memberPane.setViewportView(List);
//memberPane.setBackground(LightColor);
memberPane.setBorder(border);
memberPane.setPreferredSize(new Dimension(85, 380));
memberPane.setMinimumSize(new Dimension(85, 380));
//contentPanel.setBackground(DarkColor);
contentPanel.setBorder(border);contentPanel.setLayout(borderLayout1);
contentPanel.setPreferredSize(new Dimension(200, 380));
contentPanel.setMinimumSize(new Dimension(200, 380));
contentPanel.add(J,BorderLayout.NORTH);
contentPanel.add(JC,BorderLayout.CENTER);
contentPanel.add(J2,BorderLayout.SOUTH);
//statusPanel.setBackground(DarkColor);
statusPanel.setBorder(border);
statusPanel.setPreferredSize(new Dimension(620, 24));
statusPanel.setMinimumSize(new Dimension(620, 24));
statusPanel.setLayout(new BorderLayout());
statusPanel.add(showstatus);
this.getContentPane().setLayout(borderLayout);//this.setJMenuBar (jMenuBar);
this.getContentPane().add(toolBar, BorderLayout.NORTH);
this.getContentPane().add(memberPane, BorderLayout.EAST);
this.getContentPane().add(contentPanel, BorderLayout.CENTER);
this.getContentPane().add(statusPanel, BorderLayout.SOUTH);
}
在每次刷新在线用户列表时先删除除“所有用户”之外的所有用户
public void clear(){
for(int i=1;i<Model.getSize();i++){Model.removeElementAt(i);}
getContentPane().invalidate();
getContentPane().validate();
}
向用户列表中添加在线用户
public void add(String name){
int index =Model.getSize();
Model.addElement(name);
getContentPane().invalidate();
getContentPane().validate();
// list.setSelectedIndex(index);
// list.ensureIndexIsVisible(index);
}以上两个函数供clientt1类调用
public void valueChanged(ListSelectionEvent event) {
if (!event.getValueIsAdjusting()){str= List.getSelectedValue().toString();
if(t){
if(str.equals(mname)){JOptionPane.showMessageDialog(null,"不能跟自己交谈!");}
else try{
// input.readByte();
output.writeUTF("聊天");
output.flush();
output.writeUTF(str);
output.flush();
output.writeUTF(da2.getText().trim());
output.flush();
da.append("你对"+str+"说"+da2.getText().trim()+"\n");
da2.setText("");
}catch(Exception e){System.out.println(e);
}
//new ChatDialog(this).show();
//new ChatDialog(str,socket,output,input).show();
}
if(!t){try{ output.writeUTF("文件传输");
output.flush();
// output.close();
DataInputStream fis = new DataInputStream(new BufferedInputStream(new FileInputStream(sendFile)));
// DataOutputStream ps = new DataOutputStream(socket.getOutputStream());
output.writeUTF(str);
output.flush();
output.writeUTF(sendFile.getName());
output.flush();
output.writeLong((long) sendFile.length());
output.flush();
int bufferSize = 3000;
byte[] buf = new byte[bufferSize];
while (true) {
int read = 0;
if (fis != null) {
read = fis.read(buf);
}
if (read == -1) {
break;
}
output.write(buf, 0, read);
output.flush();
}
fis.close();
t=true;
//.close();
System.out.println("文件传输完成");
}catch (Exception ee) {
ee.printStackTrace();}
}}
}
/*public void itemStateChanged(ItemEvent evt)
{
if(evt.getStateChange() == ItemEvent.SELECTED){
str=combobox.getSelectedItem().toString();
if(t){
if(str.equals(mname)){JOptionPane.showMessageDialog(null,"不能跟自己交谈!");}
else try{
// input.readByte();
output.writeUTF("聊天");
output.flush();
output.writeUTF(str);
output.flush();
output.writeUTF(da2.getText().trim());
output.flush();
da.append(mname+"对"+str+"说"+da2.getText().trim()+"\n");
da2.setText("");
}catch(Exception e){System.out.println(e);
}
//new ChatDialog(this).show();
//new ChatDialog(str,socket,output,input).show();
}
if(!t){try{ output.writeUTF("文件传输");
output.flush();
// output.close();
DataInputStream fis = new DataInputStream(new BufferedInputStream(new FileInputStream(sendFile)));
// DataOutputStream ps = new DataOutputStream(socket.getOutputStream());
output.writeUTF(str);
output.flush();
output.writeUTF(sendFile.getName());
output.flush();
output.writeLong((long) sendFile.length());
output.flush();
int bufferSize = 3000;
byte[] buf = new byte[bufferSize];
while (true) {
int read = 0;
if (fis != null) {
read = fis.read(buf);
}
if (read == -1) {
break;
}
output.write(buf, 0, read);
output.flush();
}
fis.close();
t=true;
//.close();
System.out.println("文件传输完成");
}catch (Exception ee) {
ee.printStackTrace();}
}
}
}
*/
public void actionPerformed(ActionEvent e) {
Object o= e.getSource();
if(o==setupButton){s=new set(this,da,da2);s.show();ip=s.getIP();}
if(o==Link){Link.setEnabled(false);Leave.setEnabled(true);Connect(ip,port);}
/* if(o==Leave){Leave.setEnabled(false);Link.setEnabled(true);
try{
output.writeUTF("用户下线");
output.flush();
CT.isstop=true;
input.close();
output.close();
socket.close();
}
catch (Exception ee){
System.out.println(e);
}
}*/
if(o==helpButton){new HelpDialog(this).show();}
if(o==mp3){new Music();}
if(o==send){
t=false;
JFileChooser fc=new JFileChooser();
int returnVal=fc.showSaveDialog(Main.this);
sendFile=fc.getSelectedFile();
}
if(o==Quit){ int j=JOptionPane.showConfirmDialog(
this,"真的要退出吗?","退出",
JOptionPane.YES_OPTION,JOptionPane.QUESTION_MESSAGE);
if (j == JOptionPane.YES_OPTION){
try{
output.writeUTF("用户下线");
output.flush();
CT.isstop=true;
input.close();
output.close();
socket.close();
}
catch (Exception ee){
System.out.println(e);
}
jdbc.update("update u set Login='false' where user='"+mname+"'");
System.exit(0);
}
}
}
public void Connect(String ip,int port){
try{socket = new Socket(ip,port);
//output=new ObjectOutputStream(socket.getOutputStream());
output= new DataOutputStream(socket.getOutputStream());
// output.writeByte(0x1);
// output.flush();
//input=new ObjectInputStream(socket.getInputStream() );
input= new DataInputStream(socket.getInputStream());
output.writeUTF(mname);
output.flush();
CT=new ClientT1(this,socket,output,input, List,da,JMpane,showstatus,receiveFile);
CT.start();
}catch(Exception e){
JOptionPane.showConfirmDialog(
this,"不能连接到指定的服务器。\n请确认连接设置是否正确。","提示",
JOptionPane.DEFAULT_OPTION,JOptionPane.WARNING_MESSAGE);
return;
}
}
public static void main(String args[]) {
JFrame.setDefaultLookAndFeelDecorated(true);
JDialog.setDefaultLookAndFeelDecorated(true);
Main CH;
CH=new Main("赵宇飞");
}
}
class HelpDialog extends JDialog {//implements HyperlinkListener {
JPanel jPanel1 = new JPanel();
JPanel jPanel2 = new JPanel();
JTextArea jTextArea = new JTextArea();
BorderLayout borderLayout1 = new BorderLayout();
Border border1;
BorderLayout borderLayout2 = new BorderLayout();
JLabel MyImage = new JLabel();
JPanel Panel1 = new JPanel();
JButton Close = new JButton();
Border border2;
public HelpDialog(JFrame frame)
{
super(frame, true);
try {
jbInit();
}
catch (Exception e) {
e.printStackTrace();
}
//设置运行位置,使对话框居中
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation( (int) (screenSize.width - 416) / 2,
(int) (screenSize.height - 310) / 2);
this.setResizable(false);
}
private void jbInit() throws Exception {
border1 = BorderFactory.createEmptyBorder(20,25,50,40);
border2 = BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(
Color.lightGray,1),BorderFactory.createEmptyBorder(2,10,2,10));
this.setSize(new Dimension(416, 310));
this.setTitle("关于");
this.getContentPane().setBackground(Color.white);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
jPanel2.setBackground(Color.white);
jPanel2.setMinimumSize(new Dimension(260, 28));
jPanel2.setPreferredSize(new Dimension(260, 28));
jPanel2.setLayout(borderLayout1);
jPanel1.setBackground(Color.white);
jPanel1.setMinimumSize(new Dimension(160, 10));
jPanel1.setPreferredSize(new Dimension(160, 10));
jPanel1.setLayout(borderLayout2);
jTextArea.setBorder(border1);
jTextArea.setEditable(false);
jTextArea.setText("使用说明\n"
+"本聊天程序提供如下功能:\n"+
"1.基本网络通话功能。你可以使用本聊天程序与其他任何在线用户聊天并可向对方传输任何文件。\n"+
"2.本聊天软件附带背景音乐,你可以通过命令对背景音乐声音大小以及内容进行调整.\n"+
"3.本软件附带一些单击游戏你可以自己选择种类娱乐!");
jTextArea.setLineWrap(true);
jTextArea.setForeground(new Color(55, 77, 118));
this.getContentPane().add(jPanel1, BorderLayout.WEST);
jPanel1.add(MyImage, BorderLayout.EAST);
this.getContentPane().add(jPanel2, BorderLayout.CENTER);
jPanel2.add(jTextArea, BorderLayout.CENTER);
Close.setBackground(Color.white);
Close.setBorder(border2);
Close.setActionCommand("jButton1");
Close.setText("关闭");
Close.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
}
);
Panel1.setBackground(Color.white);
this.getContentPane().add(Panel1, BorderLayout.SOUTH);
Panel1.add(Close, null);
}
}
clientt1类:
package chat;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import javax.swing.*;
import java.lang.*;
import java.awt.*;
import javax.swing.event.*;
import java.io.*;
import java.net.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.*;
public class ClientT1 extends Thread{
Main main;
boolean isstop=false;
//JComboBox combobox;
JList List;
String receiveFile;
Socket socket;
DataOutputStream output;
DataInputStream input;
JTextArea da;
//File receiveFile;
JPanel JMpane;
JLabel showstatus = new JLabel(); //状态栏
public ClientT1(Main main1,Socket socket1,DataOutputStream output1,
DataInputStream input1,JList List1,JTextArea da1,JPanel JMpane1, JLabel showstatus1,String file){
main=main1;
List=List1;
socket=socket1;
output=output1;
input=input1;
da=da1;
JMpane=JMpane1;
showstatus=showstatus1;
receiveFile=file;
}
@Override
public void run(){
while(!isstop){
try{
String type = input.readUTF();
if(type.equalsIgnoreCase("系统信息")){
String sysmsg = input.readUTF();
da.append("系统信息: "+sysmsg+"\n");
}
else if(type.equalsIgnoreCase("服务关闭")){
input.close();
output.close();
socket.close();
da.append("服务器已关闭!\n");
break;
}
else if(type.equalsIgnoreCase("接受文件")){
// output.writeByte(0x1);
// output.flush();
// DataInputStream inputStream=new DataInputStream(socket.getInputStream());
String msg=input.readUTF();
da.append(msg);
String fname=input.readUTF();
//JFileChooser fc=new JFileChooser();
//int returnVal=fc.showSaveDialog(Chatmain.this);
// receiveFile=fc.getSelectedFile();
receiveFile+=fname;
DataOutputStream fileOut = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(receiveFile)));
while (true) {
int read = 0;
int bufferSize = 3000;
byte[] buf = new byte[bufferSize];
if (input!= null) {
read = input.read(buf);
}
else if(read == -1) {
break;
}
fileOut.write(buf, 0, read);
}
System.out.println("接收完成,文件存为" +"\n"+ receiveFile + "\n");
fileOut.close();
}
else if(type.equalsIgnoreCase("聊天")){
String message = input.readUTF();
da.append(message);
}
else if(type.equalsIgnoreCase("用户列表")){
String userlist = input.readUTF();
String usernames[] = userlist.split("\n");
main.clear();
int i =0;
while(i < usernames.length){
main.add(usernames[i]);
i ++;
}
//combobox.setSelectedIndex(0);
showstatus.setText("在线用户 " + usernames.length + " 人");
}
}
catch(Exception e ){
System.out.println(e);
}
}
}
}
客户端主要的类:ChatClient类,Main类以及ClientT1类。
ChatClient类负责用户登录界面的创建。
Main类主要负责用户聊天界面的创建。
clientt1由Main创建并启动以完成用户的通信以及文件传输功能。
ChatClient类:
其中主要包括几个类,有:JDBC类(完成数据库查询工作),Find类完成用户密码找回的动作以及Register类完成用户注册工作。
还一个用户合法性检测功能我直接写在Main里面。
ChatClient类我用的是NetBeans开发工具可视化界面编程编写的代码所以完整的不能给出仅仅给出关键代码:
(1)用户合法性检测:
具体代码后面。
Main类
package chat;
import javax.swing.event.*;
import java.io.*;
import java.net.*;
import javax.swing.*;
//
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.*;
public class Main extends JFrame implements ActionListener,ListSelectionListener{
ClientT1 CT;
JDBC jdbc=new JDBC();
set s;
String str;
// JMenuBar jMenuBar = new JMenuBar();
public String receiveFile="E:\\";
// JMenu serviceMenu = new JMenu ("功能");
// JMenuItem ting= new JMenuItem ("听歌");
//JMenuItem game= new JMenuItem ("游戏");
//JMenuItem browse=new JMenuItem ("浏览器");
//JMenuItem =new JMenuItem ("退出(X)");
File sendFile;
boolean t=true;
BorderLayout borderLayout1;
//JComboBox combobox;
JList List;
DefaultListModel Model;
String ip;
int port=8888;
Socket socket;
//ObjectOutputStream output;
//ObjectInputStream input;
DataOutputStream output;
DataInputStream input;
JLabel showstatus;
String mname;
//ChatDialog C1;
Dimension faceSize;
JTextArea da,da2;
JScrollPane memberPane,J,J2;
JPanel toolBar, JMpane, contentPanel,statusPanel,JC ;
JButton Leave,setupButton,Link,helpButton,send,mp3,Quit;
HelpDialog helpDialog;
public static JTextField statusField = new JTextField("欢迎使用QQ聊天工具");
public Main(String name) {
mname=name;
initUI();
//this.setJMenuBar(jMenuBar);
this.setResizable(false);
this.pack();
this.setSize(faceSize);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation( (int) (screenSize.width - faceSize.getWidth()) / 2,
(int) (screenSize.height - faceSize.getHeight()) / 2);
this.setTitle("QQ聊天");
ImageIcon ii = null; ii = new ImageIcon("src\\8.jpg");//C:\\Documents and Settings\\Administrator\\My Documents\\My Pictures\\8.jpg");
Image i = ii.getImage();
this.setIconImage(i);
// this.setUndecorated(true);
this.setVisible(true);
}
public void initUI() {
Font displayFont = new Font("Serif", Font.BOLD, 18);
Model = new DefaultListModel();
Model.addElement("所有人"); //文件列表
List= new JList(Model); List.setName("在线成员");
List.setFont(displayFont);
List.setVisibleRowCount(4);
List.addListSelectionListener(this);
/* jMenuBar.add (serviceMenu);
serviceMenu.add (ting);
serviceMenu.add (browse);
serviceMenu.add (game);
ting.addActionListener(this);
browse.addActionListener(this);
game.addActionListener(this);
//serviceMenu.add (exitItem);*/
Border border = BorderFactory.createBevelBorder(BevelBorder.LOWERED,
new Color(45, 92, 162),
new Color(43, 66, 97),
new Color(45, 92, 162),
new Color(84, 123, 200));
borderLayout1= new BorderLayout();
faceSize= new Dimension(350, 500);
contentPanel = new JPanel();
JPanel statusPanel = new JPanel();
toolBar = new JPanel();
showstatus=new JLabel();
da=new JTextArea("系统信息\n");//da.append("how are you ?\n");
da.setRows(15);
// da.setColumns(20);
da.setLineWrap(true);da.setEditable(false);
da2=new JTextArea("");//da2.append("how are you ?\n");
da2.setRows(6);
//da.setColumns(10);
da2.setLineWrap(true);
JC=new JPanel();JC.setSize(190,50);
J=new JScrollPane(); J.setBorder(border);
J.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
J.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
J.setSize(190,200);J.setBackground(Color.blue);
J.setViewportView(da);
J2=new JScrollPane();
J2.setBorder(border);
J2.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
J2.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
J2.setSize(190,50);J.setBackground(Color.blue);
J2.setViewportView(da2);
Quit=new JButton("退出");Quit.addActionListener(this);
BorderLayout borderLayout = new BorderLayout();
Leave=new JButton("离开");
setupButton = new JButton("设置");
Link=new JButton("连接");
helpButton = new JButton("帮助");
JButton aboutButton = new JButton("功能");
send=new JButton("文件传输");send.setBorder(null);
mp3=new JButton("mp3");mp3.setBorder(null);
mp3.setOpaque(false);mp3.setContentAreaFilled(false);
toolBar.setBorder(border);
toolBar.setPreferredSize(new Dimension(780, 35));
toolBar.setMinimumSize(new Dimension(780, 35));
toolBar.setLayout(new FlowLayout(FlowLayout.LEFT));
send.setOpaque(false);send.setContentAreaFilled(false);
Quit.setOpaque(false);Quit.setContentAreaFilled(false);Quit.setBorder(null);
setupButton.setOpaque(false);setupButton.setContentAreaFilled(false);setupButton.setBorder(null);
Link.setOpaque(false);Link.setContentAreaFilled(false);Link.setBorder(null);
helpButton.setOpaque(false);helpButton.setContentAreaFilled(false);helpButton.setBorder(null);
aboutButton.setOpaque(false);aboutButton.setContentAreaFilled(false);aboutButton.setBorder(null);
Leave.setOpaque(false);Leave.setContentAreaFilled(false);Leave.setBorder(null);
toolBar.add(setupButton); setupButton.addActionListener(this);
toolBar.add(Link); Link.addActionListener(this);
toolBar.add(helpButton); helpButton.addActionListener(this);
toolBar.add(aboutButton); aboutButton.addActionListener(this);
//toolBar.add(Leave);
//Leave.addActionListener(this);
// toolBar.add(serviceMenu);
toolBar.add(send); send.addActionListener(this);
mp3.addActionListener(this);
toolBar.add(mp3);
toolBar.add(Quit);
/*combobox = new JComboBox();
combobox.insertItemAt("所有人",0);
combobox.setSelectedIndex(0);
JPanel JMpane=new JPanel();JMpane.setSize(40,2000);JMpane.setLayout(new GridLayout(2000,1));
JMpane.add(combobox);//combobox.addItem("jasstion");
combobox.addItemListener(this);*/
memberPane= new JScrollPane();
memberPane.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
memberPane.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
memberPane.setSize(190,380);J.setBackground(Color.blue);
memberPane.setViewportView(List);
//memberPane.setBackground(LightColor);
memberPane.setBorder(border);
memberPane.setPreferredSize(new Dimension(85, 380));
memberPane.setMinimumSize(new Dimension(85, 380));
//contentPanel.setBackground(DarkColor);
contentPanel.setBorder(border);contentPanel.setLayout(borderLayout1);
contentPanel.setPreferredSize(new Dimension(200, 380));
contentPanel.setMinimumSize(new Dimension(200, 380));
contentPanel.add(J,BorderLayout.NORTH);
contentPanel.add(JC,BorderLayout.CENTER);
contentPanel.add(J2,BorderLayout.SOUTH);
//statusPanel.setBackground(DarkColor);
statusPanel.setBorder(border);
statusPanel.setPreferredSize(new Dimension(620, 24));
statusPanel.setMinimumSize(new Dimension(620, 24));
statusPanel.setLayout(new BorderLayout());
statusPanel.add(showstatus);
this.getContentPane().setLayout(borderLayout);//this.setJMenuBar (jMenuBar);
this.getContentPane().add(toolBar, BorderLayout.NORTH);
this.getContentPane().add(memberPane, BorderLayout.EAST);
this.getContentPane().add(contentPanel, BorderLayout.CENTER);
this.getContentPane().add(statusPanel, BorderLayout.SOUTH);
}
在每次刷新在线用户列表时先删除除“所有用户”之外的所有用户
public void clear(){
for(int i=1;i<Model.getSize();i++){Model.removeElementAt(i);}
getContentPane().invalidate();
getContentPane().validate();
}
向用户列表中添加在线用户
public void add(String name){
int index =Model.getSize();
Model.addElement(name);
getContentPane().invalidate();
getContentPane().validate();
// list.setSelectedIndex(index);
// list.ensureIndexIsVisible(index);
}以上两个函数供clientt1类调用
public void valueChanged(ListSelectionEvent event) {
if (!event.getValueIsAdjusting()){str= List.getSelectedValue().toString();
if(t){
if(str.equals(mname)){JOptionPane.showMessageDialog(null,"不能跟自己交谈!");}
else try{
// input.readByte();
output.writeUTF("聊天");
output.flush();
output.writeUTF(str);
output.flush();
output.writeUTF(da2.getText().trim());
output.flush();
da.append("你对"+str+"说"+da2.getText().trim()+"\n");
da2.setText("");
}catch(Exception e){System.out.println(e);
}
//new ChatDialog(this).show();
//new ChatDialog(str,socket,output,input).show();
}
if(!t){try{ output.writeUTF("文件传输");
output.flush();
// output.close();
DataInputStream fis = new DataInputStream(new BufferedInputStream(new FileInputStream(sendFile)));
// DataOutputStream ps = new DataOutputStream(socket.getOutputStream());
output.writeUTF(str);
output.flush();
output.writeUTF(sendFile.getName());
output.flush();
output.writeLong((long) sendFile.length());
output.flush();
int bufferSize = 3000;
byte[] buf = new byte[bufferSize];
while (true) {
int read = 0;
if (fis != null) {
read = fis.read(buf);
}
if (read == -1) {
break;
}
output.write(buf, 0, read);
output.flush();
}
fis.close();
t=true;
//.close();
System.out.println("文件传输完成");
}catch (Exception ee) {
ee.printStackTrace();}
}}
}
/*public void itemStateChanged(ItemEvent evt)
{
if(evt.getStateChange() == ItemEvent.SELECTED){
str=combobox.getSelectedItem().toString();
if(t){
if(str.equals(mname)){JOptionPane.showMessageDialog(null,"不能跟自己交谈!");}
else try{
// input.readByte();
output.writeUTF("聊天");
output.flush();
output.writeUTF(str);
output.flush();
output.writeUTF(da2.getText().trim());
output.flush();
da.append(mname+"对"+str+"说"+da2.getText().trim()+"\n");
da2.setText("");
}catch(Exception e){System.out.println(e);
}
//new ChatDialog(this).show();
//new ChatDialog(str,socket,output,input).show();
}
if(!t){try{ output.writeUTF("文件传输");
output.flush();
// output.close();
DataInputStream fis = new DataInputStream(new BufferedInputStream(new FileInputStream(sendFile)));
// DataOutputStream ps = new DataOutputStream(socket.getOutputStream());
output.writeUTF(str);
output.flush();
output.writeUTF(sendFile.getName());
output.flush();
output.writeLong((long) sendFile.length());
output.flush();
int bufferSize = 3000;
byte[] buf = new byte[bufferSize];
while (true) {
int read = 0;
if (fis != null) {
read = fis.read(buf);
}
if (read == -1) {
break;
}
output.write(buf, 0, read);
output.flush();
}
fis.close();
t=true;
//.close();
System.out.println("文件传输完成");
}catch (Exception ee) {
ee.printStackTrace();}
}
}
}
*/
public void actionPerformed(ActionEvent e) {
Object o= e.getSource();
if(o==setupButton){s=new set(this,da,da2);s.show();ip=s.getIP();}
if(o==Link){Link.setEnabled(false);Leave.setEnabled(true);Connect(ip,port);}
/* if(o==Leave){Leave.setEnabled(false);Link.setEnabled(true);
try{
output.writeUTF("用户下线");
output.flush();
CT.isstop=true;
input.close();
output.close();
socket.close();
}
catch (Exception ee){
System.out.println(e);
}
}*/
if(o==helpButton){new HelpDialog(this).show();}
if(o==mp3){new Music();}
if(o==send){
t=false;
JFileChooser fc=new JFileChooser();
int returnVal=fc.showSaveDialog(Main.this);
sendFile=fc.getSelectedFile();
}
if(o==Quit){ int j=JOptionPane.showConfirmDialog(
this,"真的要退出吗?","退出",
JOptionPane.YES_OPTION,JOptionPane.QUESTION_MESSAGE);
if (j == JOptionPane.YES_OPTION){
try{
output.writeUTF("用户下线");
output.flush();
CT.isstop=true;
input.close();
output.close();
socket.close();
}
catch (Exception ee){
System.out.println(e);
}
jdbc.update("update u set Login='false' where user='"+mname+"'");
System.exit(0);
}
}
}
public void Connect(String ip,int port){
try{socket = new Socket(ip,port);
//output=new ObjectOutputStream(socket.getOutputStream());
output= new DataOutputStream(socket.getOutputStream());
// output.writeByte(0x1);
// output.flush();
//input=new ObjectInputStream(socket.getInputStream() );
input= new DataInputStream(socket.getInputStream());
output.writeUTF(mname);
output.flush();
CT=new ClientT1(this,socket,output,input, List,da,JMpane,showstatus,receiveFile);
CT.start();
}catch(Exception e){
JOptionPane.showConfirmDialog(
this,"不能连接到指定的服务器。\n请确认连接设置是否正确。","提示",
JOptionPane.DEFAULT_OPTION,JOptionPane.WARNING_MESSAGE);
return;
}
}
public static void main(String args[]) {
JFrame.setDefaultLookAndFeelDecorated(true);
JDialog.setDefaultLookAndFeelDecorated(true);
Main CH;
CH=new Main("赵宇飞");
}
}
class HelpDialog extends JDialog {//implements HyperlinkListener {
JPanel jPanel1 = new JPanel();
JPanel jPanel2 = new JPanel();
JTextArea jTextArea = new JTextArea();
BorderLayout borderLayout1 = new BorderLayout();
Border border1;
BorderLayout borderLayout2 = new BorderLayout();
JLabel MyImage = new JLabel();
JPanel Panel1 = new JPanel();
JButton Close = new JButton();
Border border2;
public HelpDialog(JFrame frame)
{
super(frame, true);
try {
jbInit();
}
catch (Exception e) {
e.printStackTrace();
}
//设置运行位置,使对话框居中
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation( (int) (screenSize.width - 416) / 2,
(int) (screenSize.height - 310) / 2);
this.setResizable(false);
}
private void jbInit() throws Exception {
border1 = BorderFactory.createEmptyBorder(20,25,50,40);
border2 = BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(
Color.lightGray,1),BorderFactory.createEmptyBorder(2,10,2,10));
this.setSize(new Dimension(416, 310));
this.setTitle("关于");
this.getContentPane().setBackground(Color.white);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
jPanel2.setBackground(Color.white);
jPanel2.setMinimumSize(new Dimension(260, 28));
jPanel2.setPreferredSize(new Dimension(260, 28));
jPanel2.setLayout(borderLayout1);
jPanel1.setBackground(Color.white);
jPanel1.setMinimumSize(new Dimension(160, 10));
jPanel1.setPreferredSize(new Dimension(160, 10));
jPanel1.setLayout(borderLayout2);
jTextArea.setBorder(border1);
jTextArea.setEditable(false);
jTextArea.setText("使用说明\n"
+"本聊天程序提供如下功能:\n"+
"1.基本网络通话功能。你可以使用本聊天程序与其他任何在线用户聊天并可向对方传输任何文件。\n"+
"2.本聊天软件附带背景音乐,你可以通过命令对背景音乐声音大小以及内容进行调整.\n"+
"3.本软件附带一些单击游戏你可以自己选择种类娱乐!");
jTextArea.setLineWrap(true);
jTextArea.setForeground(new Color(55, 77, 118));
this.getContentPane().add(jPanel1, BorderLayout.WEST);
jPanel1.add(MyImage, BorderLayout.EAST);
this.getContentPane().add(jPanel2, BorderLayout.CENTER);
jPanel2.add(jTextArea, BorderLayout.CENTER);
Close.setBackground(Color.white);
Close.setBorder(border2);
Close.setActionCommand("jButton1");
Close.setText("关闭");
Close.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
}
);
Panel1.setBackground(Color.white);
this.getContentPane().add(Panel1, BorderLayout.SOUTH);
Panel1.add(Close, null);
}
}
clientt1类:
package chat;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import javax.swing.*;
import java.lang.*;
import java.awt.*;
import javax.swing.event.*;
import java.io.*;
import java.net.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.*;
public class ClientT1 extends Thread{
Main main;
boolean isstop=false;
//JComboBox combobox;
JList List;
String receiveFile;
Socket socket;
DataOutputStream output;
DataInputStream input;
JTextArea da;
//File receiveFile;
JPanel JMpane;
JLabel showstatus = new JLabel(); //状态栏
public ClientT1(Main main1,Socket socket1,DataOutputStream output1,
DataInputStream input1,JList List1,JTextArea da1,JPanel JMpane1, JLabel showstatus1,String file){
main=main1;
List=List1;
socket=socket1;
output=output1;
input=input1;
da=da1;
JMpane=JMpane1;
showstatus=showstatus1;
receiveFile=file;
}
@Override
public void run(){
while(!isstop){
try{
String type = input.readUTF();
if(type.equalsIgnoreCase("系统信息")){
String sysmsg = input.readUTF();
da.append("系统信息: "+sysmsg+"\n");
}
else if(type.equalsIgnoreCase("服务关闭")){
input.close();
output.close();
socket.close();
da.append("服务器已关闭!\n");
break;
}
else if(type.equalsIgnoreCase("接受文件")){
// output.writeByte(0x1);
// output.flush();
// DataInputStream inputStream=new DataInputStream(socket.getInputStream());
String msg=input.readUTF();
da.append(msg);
String fname=input.readUTF();
//JFileChooser fc=new JFileChooser();
//int returnVal=fc.showSaveDialog(Chatmain.this);
// receiveFile=fc.getSelectedFile();
receiveFile+=fname;
DataOutputStream fileOut = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(receiveFile)));
while (true) {
int read = 0;
int bufferSize = 3000;
byte[] buf = new byte[bufferSize];
if (input!= null) {
read = input.read(buf);
}
else if(read == -1) {
break;
}
fileOut.write(buf, 0, read);
}
System.out.println("接收完成,文件存为" +"\n"+ receiveFile + "\n");
fileOut.close();
}
else if(type.equalsIgnoreCase("聊天")){
String message = input.readUTF();
da.append(message);
}
else if(type.equalsIgnoreCase("用户列表")){
String userlist = input.readUTF();
String usernames[] = userlist.split("\n");
main.clear();
int i =0;
while(i < usernames.length){
main.add(usernames[i]);
i ++;
}
//combobox.setSelectedIndex(0);
showstatus.setText("在线用户 " + usernames.length + " 人");
}
}
catch(Exception e ){
System.out.println(e);
}
}
}
}