当前位置: 代码迷 >> Java相关 >> 高手帮忙!!!!!!!!救命啊。。。。
  详细解决方案

高手帮忙!!!!!!!!救命啊。。。。

热度:514   发布时间:2007-12-24 23:55:58.0
高手帮忙!!!!!!!!救命啊。。。。
//服务器程序

请注意红色字段
//Tang
package serverDemo;

import java.io.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ChatServerDemo extends Thread implements ActionListener
{
    //声明一个ServerSocket
    ServerSocket serverSockets;
    Socket clientSockets;
    //构建服务器的窗体
    static JFrame frm = new JFrame("服务器启动......");
    static JPanel pnl = new JPanel();
    static JTextArea txtMsn = new JTextArea(26,26);
    static JScrollPane scp;
    static JButton btnAbout = new JButton("关   于");
    static JButton btnShowUser = new JButton("显示已注册用户名");
    static JComboBox cbbOnlineUser = new JComboBox();
    static JLabel lblOnlineUser = new JLabel("已经上线用户:");
    static JTextField txtChat = new JTextField();
    static JButton btnSend = new JButton("发  送");
    static JButton btnExit = new JButton("强制用户下线");
    javax.swing.Timer timers;
    
    //构造函数(ChatServerDemo()的用户数组)
    static ArrayList nameList = new ArrayList();
    static ArrayList socketArray = new ArrayList();
    
    public ChatServerDemo()
    {
////////////////////////////////////////////窗体////////////////////////////////////////////////////////////////////////////////
        pnl.setLayout(null);                   //取消布局
        scp = new JScrollPane(txtMsn);
        cbbOnlineUser.addItem("所有用户");
        
        pnl.add(scp);
        pnl.add(btnAbout);
        pnl.add(btnShowUser);
        pnl.add(lblOnlineUser);
        pnl.add(cbbOnlineUser);
        pnl.add(txtChat);
        pnl.add(btnSend);
        pnl.add(btnExit);
        
        txtMsn.setEditable(false);             //使用户不能向txtMsn添加信息
        frm.setResizable(false);               //使窗体大小固定
        int w = (Toolkit.getDefaultToolkit().getScreenSize().width - frm.WIDTH) / 5;      //窗体在屏幕位置
        int h = (Toolkit.getDefaultToolkit().getScreenSize().height - frm.HEIGHT) / 5;
        frm.setLocation(w, h);
        frm.setIconImage(Toolkit.getDefaultToolkit().getImage("picture/two.jpg"));                //JFrame图片
        
        scp.setBounds(new Rectangle(5, 5, 600, 480));                   //绝对布局
        btnAbout.setBounds(new Rectangle(610, 5, 85, 25));
        btnShowUser.setBounds(new Rectangle(610, 460, 140, 25));
        btnExit.setBounds(new Rectangle(610, 430, 140, 25));
        cbbOnlineUser.setBounds(new Rectangle(610, 400, 140, 25));
        lblOnlineUser.setBounds(new Rectangle(610, 375, 140, 25));
        txtChat.setBounds(new Rectangle(5, 500, 420, 30));
        btnSend.setBounds(new Rectangle(440, 500, 80, 30));
        
        btnAbout.setFont(new Font("\u5b8b\u4f53", Font.PLAIN, 13));
        btnShowUser.setFont(new Font("\u5b8b\u4f53", Font.PLAIN, 13));     //字体
        cbbOnlineUser.setFont(new Font("\u5b8b\u4f53", Font.PLAIN, 13));
        lblOnlineUser.setFont(new Font("\u5b8b\u4f53", Font.PLAIN, 13));
        btnSend.setFont(new Font("\u5b8b\u4f53", Font.PLAIN, 13));
        btnExit.setFont(new Font("\u5b8b\u4f53", Font.PLAIN, 13));
        
        btnAbout.addActionListener(this);  
        btnShowUser.addActionListener(this);  
        btnSend.addActionListener(this);  
                                     //
        frm.getContentPane().add(pnl);
        frm.setSize(800,600);
        frm.setVisible(true);
        frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        //使txtMsn自动向下滚动
        timers =new javax.swing.Timer(2000,new ActionListener()  
        {  
          public void actionPerformed(ActionEvent   e)  
          {  
               txtMsn.setCaretPosition(txtMsn.getDocument().getLength()-0);  
           }  
        });  
        timers.start();
        
        //ServerSocket构建
        try
        {
            serverSockets = new ServerSocket(9394);      
            start();
            ChatServerDemo.txtMsn.append("服务器正常启动......\n");
        }
        catch(IOException ext)
        {
            ChatServerDemo.txtMsn.append("服务器已经运行了,操作错误......\n");
        }
        
    }

    public void actionPerformed(ActionEvent evt)
    {
        if(evt.getSource()==btnAbout)
        {
            JOptionPane.showMessageDialog(null,"JAVA聊天室服务器\n版本号:v1.031\n");
        }
        
        if(evt.getSource()==btnShowUser)
        {
            try
            {
                BufferedReader fromFile = new BufferedReader(new FileReader("server/users.txt"));
                String fromFileMsn = null;
                ChatServerDemo.txtMsn.append("\n");
                int i = 1;
                while((fromFileMsn = fromFile.readLine()) != null)
                {
                    StringTokenizer userMsnToken = new StringTokenizer(fromFileMsn,":");
                    String userName = userMsnToken.nextToken();
                    ChatServerDemo.txtMsn.append("已注册用户"+i+"的用户名为:"+userName+"\n");
                    i++;
                }
                ChatServerDemo.txtMsn.append("\n");
            }
            catch(IOException ext)
            {
                ChatServerDemo.txtMsn.append("读取已经注册用户出错......\n");
            }
        }
        if(evt.getSource()==btnSend)
        {
            PrintWriter serverToClient;
            txtChat.requestFocusInWindow();
            String serverMsn = txtChat.getText();
            txtMsn.append("管理员对大家说:"+serverMsn+"\n");
            txtChat.setText("");
            for(int i=0;i<ChatServerDemo.socketArray.size();i++)
            {
                我如何调用下面的   红色字段            }
        }
    }
    
    //
    public void run()
    {
        //不断接受客户端的信息
        while(true)
        {
            try
            {
                //不断接受连接的客户端
                clientSockets = serverSockets.accept();
                //判断是否有客户连接上来,若有就执行
                if(clientSockets != null)
                {
                    //实现登录,注册,聊天的类
                    MyConnection con = new MyConnection(clientSockets);
                }
            }
            catch(IOException ext)
            {
                ChatServerDemo.txtMsn.append("run()的Socket出错......"+ext.toString()+"\n");    
            }
        }
    }
    
    //构建main函数
    public static void main(String args[])
    {
        ChatServerDemo chatServerObj = new ChatServerDemo();
    }
}

//实现登录,注册,聊天的类

class MyConnection extends Thread
{
    Socket clientSockets;
    ObjectInputStream serverFromClient;
    PrintWriter serverToClient;
    
    //构造MyConnection方法
    public MyConnection(Socket sockets)
    {
        try
        {
            this.clientSockets = sockets;
            serverFromClient = new ObjectInputStream(clientSockets.getInputStream());
            serverToClient = new PrintWriter(clientSockets.getOutputStream());
            start();
        }
        catch(IOException ext)
        {
            ChatServerDemo.txtMsn.append("MyConnection()构造出错......"+ext.toString()+"\n");
        }
    }
    
    public void run()
    {
        while(true)
        {
            try
            {
                String MsnForClient = null;
                //只要客户端的信息不为空就执行
                if((MsnForClient = serverFromClient.readObject().toString())!= null)
                {
                    //将信息分类出来
                    StringTokenizer clientMsnToken = new StringTokenizer(MsnForClient,"|");
                    String firstInfo = clientMsnToken.nextToken();
                    String msn = clientMsnToken.nextToken(); //用户的主要信息
                    //将分类出来的信息做相应的工作
                    //注册信息
                    if(firstInfo.equals("register"))
                    {
                        register(msn);
                    }
                    //登录信息
                    if(firstInfo.equals("login"))
                    {
                        login(msn);
                    }
                    //聊天信息
                    if(firstInfo.equals("chat"))
                    {
                        chat(msn);
                    }
                    if(firstInfo.equals("exit"))
                    {
                        exit(msn);
                    }
                }
            }
            catch(IOException ext)
            {
                ChatServerDemo.txtMsn.append("有一用户关闭了程序......\n");
                break;
            }
            catch(ClassNotFoundException ext)
            {
                ChatServerDemo.txtMsn.append("MyConnection的run(2)方法出错......"+ext.toString()+"\n");
                break;
            }
            
        }
    }    
    //聊天函数
    private void chat(String chatMsn)
    {
        StringTokenizer msnToken = new StringTokenizer(chatMsn,":");
        String divisionMsn = msnToken.nextToken();
        String name = msnToken.nextToken();
        String msn = msnToken.nextToken();
        
        if(!divisionMsn.equals("所有用户"))
        {
            ChatServerDemo.txtMsn.append(name+"悄悄地对[ "+divisionMsn+" ]说:"+msn+"\n");
        }
        else
        {
            ChatServerDemo.txtMsn.append(name+"对大家说:"+msn+"\n");
        }
        
        for(int i=0;i<ChatServerDemo.socketArray.size();i++)
        {
            try
            {
                Socket nowSocket = (Socket)ChatServerDemo.socketArray.get(i);
                serverToClient = new PrintWriter(nowSocket.getOutputStream(),true);
                serverToClient.write("publicMsn|"+chatMsn+"\n");
                serverToClient.flush();
            }
            catch(Exception ex)
            {
                ChatServerDemo.txtMsn.append("聊天出问题\n");
            }
        }
    }
    
    //下线函数
    private void exit(String exitMsn)
    {
        ChatServerDemo.txtMsn.append(exitMsn+"\n");
        StringTokenizer exitMsg = new StringTokenizer(exitMsn);
        String itIsNoUse = exitMsg.nextToken();
        String exitName = exitMsg.nextToken();
        //用于铲除数组中的下线用户
        for(int i=0;i<ChatServerDemo.nameList.size();i++)
        {
            if(exitName.equals(ChatServerDemo.nameList.get(i)))
            {
                ChatServerDemo.nameList.remove(exitName);
                ChatServerDemo.cbbOnlineUser.removeItem(exitName);
            }
        }
        String allUsers = "所有用户";
        for(int i=0;i<ChatServerDemo.nameList.size();i++)
        {
            allUsers += ":" + (String)ChatServerDemo.nameList.get(i);    //装载nameList中的在线用户
        }
        String allUserNames = "userOnlineNames|" + allUsers;
        for(int i=0;i<ChatServerDemo.socketArray.size();i++)                                  //
        {                                                                                 //
            Socket socketForClient = (Socket)ChatServerDemo.socketArray.get(i);               //
            try                                                                              //
            {                                                                             //
                serverToClient = new PrintWriter(socketForClient.getOutputStream(),true); //响每个在线用户
                serverToClient.println(allUserNames);                                     // 发送allUserNames
            }                                                                             //
            catch(IOException ex)                                                         //
            {                                                                             //
                 ChatServerDemo.txtMsn.append("在线用户名发送出错"+ex.toString()+"\n");       //
            }                                                                             //
        }
    }
}
搜索更多相关的解决方案: 救命  

----------------解决方案--------------------------------------------------------
  相关解决方案