当前位置: 代码迷 >> Java相关 >> 最近写聊天室程序遇到麻烦了`有人来帮一把么?
  详细解决方案

最近写聊天室程序遇到麻烦了`有人来帮一把么?

热度:379   发布时间:2009-11-05 21:50:17.0
最近写聊天室程序遇到麻烦了`有人来帮一把么?
Server:

程序代码:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.*;
import java.util.Scanner;
   

public class Server extends Thread{
    public static String[] vs = new String[10];
    public static int i =0;
     Socket socket;
   
    public  void run(){
        try{
            ServerSocket server = new ServerSocket(1600);
            while(true){
                System.out.println("服务器启动中......");
                socket = server.accept();
                ClientLine client = new ClientLine(socket);
                client.start();
                }
            }catch(IOException e){
                System.out.println("程序关闭....");
                System.exit(0);
        }
    }
   
    public static synchronized void message(String msg){
        vs[i] = msg;
        i = (i+1)%10;
        vs[i] = "*";   
    }
   
    public static void main(String args[]){
        new Server().start();   
    }
   
}


class ClientLine extends Thread {
   
    Socket client;
    String msg;
    BufferedReader in;
    PrintWriter out;
    ClientLine(Socket socket){
        this.client = socket;
    }
    public void run(){
        try{
            
            in = new BufferedReader(new InputStreamReader(
                                              client.getInputStream()));
            out = new PrintWriter(client.getOutputStream());
            
            SendToAll send = new SendToAll();
            send.start();
            msg = in.readLine();
            while(!msg.equals("exit")){
                Server.message(msg);
                msg = in.readLine();
            }
            if(msg.equals("exit")){
                in.close();
                out.close();
                client.close();            
            }
            
            }catch(IOException e){
                System.out.println("出现异常!");        
        }
    }
    public class SendToAll extends Thread{
        private int j = 0;
        public void run(){
            while(true){
        
                try{
                sleep(500);
                }catch(InterruptedException e){
                    System.out.println("同步错误....");
                    
                }
                while(true){
                    if(!Server.vs[j].equals("*")){
                        out.println(Server.vs[j]);
                        out.flush();
                        j = (j+1)%10;
                    }
               
                }
            }
            
        }
    }
}
Client:
程序代码:

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

class Client extends JFrame{
    JLabel l1;
    JTextField text1;
    JTextArea ta,tt;
    JButton b1,b2;
    JPanel p1,p2;
    Socket socket = null;
    BufferedReader in;
    PrintWriter out;
    String b,c;
   
    Client(){
        //设定窗口,并建立两个按钮事件`
            setSize(400,400);
            setLocation(300,300);
            setVisible(true);
            Container cp = getContentPane();
            cp.setLayout(new BorderLayout());
            l1 = new JLabel("请输入你的昵称:");   
            text1 = new JTextField(10);
            b1 = new JButton("建立连接");
            b1.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e){    //按钮事件`
                    l1.setEnabled(false);
                    text1.setEditable(false);
                    b1.setEnabled(false);
                    repaint();
                    count();                            //调用连接方法` 开始连接`
                    
                }
            });
            b2 = new JButton("发送");
            b2.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e){
                    b = ta.getText();
                    out.print(b);                    
                    ta.setText("");   
                }
            });
            p1 = new JPanel(new FlowLayout(FlowLayout.CENTER));
            p2 = new JPanel(new BorderLayout());
            ta = new JTextArea(5,1);
            tt = new JTextArea();
            tt.setEditable(false);
            cp.add(p2,BorderLayout.SOUTH);
            cp.add(p1,BorderLayout.NORTH);
            JScrollPane scroll1 = new JScrollPane(tt);
            cp.add(scroll1,BorderLayout.CENTER);
            p1.add(l1);
            p1.add(text1);
            p1.add(b1);   
            JScrollPane scroll = new JScrollPane(ta);
            p2.add(scroll,BorderLayout.CENTER);
            p2.add(b2,BorderLayout.EAST);
            repaint();
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        
        
    }
    public void count(){                                //定义建立连接的方法
        try{
        socket = new Socket("127.0.0.1",1600);
        }catch(IOException a){System.out.println("找不到服务器");}

        try{
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        out = new PrintWriter(socket.getOutputStream());
        new ClientThread().start();
        }catch(IOException Ee){ System.out.println("连接异常");}
    }
               
    class ClientThread extends Thread{
        public void run(){
            String msg;
                try{
                    msg = in.readLine();
                    while(true){
                        tt.append(msg+"\n");
                        msg = in.readLine();
                    }
                }catch(IOException e){
                    System.out.println("连接异常!");}
        }
    }
    public static void main(String args[]){
        new Client();
    }
}

这是仿照网上的一个聊天室代码写的`
但为什么连接后主程序会出现空指针异常呢`
大体的部分都和那个程序差不多啊`
原程序见附件`
搜索更多相关的解决方案: 麻烦  聊天室  

----------------解决方案--------------------------------------------------------
代码比较长
看看这个吧
程序代码:

程序代码:
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;

public class ChatClient extends Frame
{
    TextArea ta = new TextArea();
    TextField tf = new TextField();
    public void launchFrame() throws Exception
    {
        this.add(ta, BorderLayout.CENTER);
        this.add(tf, BorderLayout.SOUTH);
        tf.addActionListener(
            new ActionListener()
            {
                public void actionPerformed(ActionEvent ae)
                {
                    try {
                        String sSend = tf.getText();
                        if(sSend.trim().length() == 0) return;
                        ChatClient.this.send(sSend);
                        tf.setText("");
                        ta.append(sSend + "\n");
                    }
                    catch (Exception e) { e.printStackTrace(); }
                }
            }
            );
        
        this.addWindowListener(
            new WindowAdapter()
            {
                public void windowClosing(WindowEvent e)
                {
                    System.exit(0);
                }
            }
            );
        setBounds(300,300,300,400);
        setVisible(true);
        tf.requestFocus();
    }
   
    Socket s = null;
   
    public ChatClient() throws Exception
    {
        s = new Socket("127.0.0.1", 8888);
        launchFrame();
        (new Thread(new ReceiveThread())).start();
    }
   
    public void send(String str) throws Exception
    {
        DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        dos.writeUTF(str);
    }
   
    public void disconnect() throws Exception
    {
        s.close();
    }
   
    public static void main(String[] args) throws Exception
    {
        BufferedReader br = new BufferedReader (
                                new InputStreamReader(System.in));
        ChatClient cc = new ChatClient();
        String str = br.readLine();
        while(str != null && str.length() != 0)
        {
            cc.send(str);
            str = br.readLine();
        }
        cc.disconnect();
    }
   
    class ReceiveThread implements Runnable
    {
        public void run()
        {
            if(s == null) return;
            try {
                DataInputStream dis = new DataInputStream(s.getInputStream());
                String str = dis.readUTF();
                while (str != null && str.length() != 0)
                {
                    //System.out.println(str);
                    ChatClient.this.ta.append(str + "\n");
                    str = dis.readUTF();
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            
        }
   
}
}

程序代码:

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

public class ChatServer extends Frame
{
    TextArea ta = new TextArea();
    public void launchFrame()
    {
        add(ta, BorderLayout.CENTER);
        setBounds(0,0,200,300);   
        this.addWindowListener(
            new WindowAdapter()
            {
                public void windowClosing(WindowEvent e)
                {
                    System.exit(0);
                }
            }
            );
        setVisible(true);
    }
   
    ServerSocket server = null;
    Collection cClient = new ArrayList();
   
    public ChatServer(int port) throws Exception
    {
        server = new ServerSocket(port);
        launchFrame();
    }
   
    public void startServer() throws Exception
    {
        while(true)
        {
            Socket s = server.accept();
            cClient.add( new ClientConn(s) );
            ta.append("NEW-CLIENT " + s.getInetAddress() + ":" + s.getPort());
            ta.append("\n" + "CLIENTS-COUNT: " + cClient.size() + "\n\n");
        }
    }
   
    class ClientConn implements Runnable
    {
        Socket s = null;
        public ClientConn(Socket s)
        {
            this.s = s;
            (new Thread(this)).start();
        }
        
        public void send(String str) throws IOException
        {
            DataOutputStream dos = new DataOutputStream(s.getOutputStream());
            dos.writeUTF(str);
        }
        
        public void dispose()
        {
            try {
                if (s != null) s.close();
                cClient.remove(this);
                ta.append("A client out! \n");
                ta.append("CLIENT-COUNT: " + cClient.size() + "\n\n");
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        
        public void run()
        {
            try {
               
                DataInputStream dis = new DataInputStream(s.getInputStream());
                String str = dis.readUTF();
                while(str != null && str.length() !=0)
                {
                    System.out.println(str);
                    for(Iterator it = cClient.iterator(); it.hasNext(); )
                    {
                        ClientConn cc = (ClientConn)it.next();
                        if(this != cc)
                        {
                            cc.send(str);
                        }
                    }
                    str = dis.readUTF();
                    //send(str);
                }
                this.dispose();
            }
            catch (Exception e)
            {
                System.out.println("client quit");
                this.dispose();
            }
            
        }
    }
   
    public static void main(String[] args) throws Exception
    {
        ChatServer cs = new ChatServer(8888);
        cs.startServer();
    }
}



[ 本帖最后由 pywepe 于 2009-11-6 08:56 编辑 ]
----------------解决方案--------------------------------------------------------
  相关解决方案