| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 556 人关注过本帖
标题:最近写聊天室程序遇到麻烦了`有人来帮一把么?
只看楼主 加入收藏
chump345
Rank: 1
来 自:家里蹲大学
等 级:新手上路
帖 子:108
专家分:5
注 册:2007-11-24
结帖率:93.33%
收藏
已结贴  问题点数:20 回复次数:1 
最近写聊天室程序遇到麻烦了`有人来帮一把么?
Server:

程序代码:
import     *;
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 *;
import *;

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();
    }
}

这是仿照网上的一个聊天室代码写的`
但为什么连接后主程序会出现空指针异常呢`
大体的部分都和那个程序差不多啊`
原程序见附件`
原程序.rar (3.31 KB)
搜索更多相关主题的帖子: 麻烦 聊天室 
2009-11-05 21:50
pywepe
Rank: 6Rank: 6
等 级:侠之大者
威 望:4
帖 子:296
专家分:483
注 册:2009-4-5
收藏
得分:20 
代码比较长
看看这个吧
程序代码:
import *;
import *;
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 *;
import java.util.*;
import *;
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 编辑 ]

java群
62635216
欢迎加入
2009-11-06 08:53
快速回复:最近写聊天室程序遇到麻烦了`有人来帮一把么?
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.050885 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved