给你一个保证能运行的吧,appServer为服务器,clent那个为客户的//AppServer.java
/**
*soloist 
*/
import java.awt.event.*;
import java.net.*;
import java.io.*;
import java.util.*;
import javax.swing.Timer;//Code for the AppServer classpublic class AppServer implements Runnable
{ ServerSocket server;
Socket fromClient;
Thread serverThread; public AppServer()
{
    System.out.print("Chat server started..........");
        try
{
server = new ServerSocket(1001);
serverThread = new Thread(this);
serverThread.start();
}
catch(Exception e)
{
System.out.println("Cannot start the thread: " + e);
}
}
public static void main(String args[])
{
new AppServer(); } public void run()
{
try
{
while(true)
{
//Listening to the clients request
fromClient = server.accept();
//Creating the connect object
Connect con = new Connect(fromClient);
}
}
catch(Exception e)
{
       System.out.println("Cannot listen to the client" + e);
}
}}//Code for the connect class
class Connect
{
    ObjectOutputStream streamToClient;
int ctr=0; BufferedReader streamFromClient;
    static Vector vector;
static Vector vctrList;
String message=" ";
static String str=new String("UsrList");    static
{
       vector=new Vector(1,1);
   vctrList=new Vector(1,1);
   vctrList.addElement((String)str);
}
int verify(String mesg)
        { try
{
RandomAccessFile RAS=new RandomAccessFile("UsrPwd.txt", "r");
int i=0;
String str="";
while((RAS.getFilePointer())!=(RAS.length())) //getFilePointer()用于了解当前在文件的什么地方
{
str=RAS.readLine();
if(str.equals(mesg))
{
ctr=1;
break; }
}
RAS.close();
}
catch(Exception e)
{ } return ctr;
}//end of verify()int checkFile(String mesg)
{
int chk=1;
try
{
RandomAccessFile RS=new RandomAccessFile("UsrPwd.txt", "r");
int i=0; String str="";
String colon=new String(":");
int index=((String)mesg).lastIndexOf(colon); String userName=(String)mesg.substring(0,index);
while((RS.getFilePointer())!=(int)(RS.length()))
{
str=RS.readLine();
int index1=((String)str).lastIndexOf(colon);
String usrName=(String)str.substring(0,index1);
if(usrName.equals(userName))
{
chk=0;
break; }
}//end of while
RS.close();
}//end of try
catch(Exception e)
{ } return chk;
}//end of chkFile
public Connect(Socket inFromClient)
{
//Retrieving the clients stream
String msg="";
String mesg="";
try
{
streamFromClient = new  BufferedReader(new InputStreamReader(inFromClient.getInputStream()));            streamToClient= new ObjectOutputStream(inFromClient.getOutputStream()); msg=streamFromClient.readLine();
//mesg=streamFromClient.readLine(); if((msg.equals("From Timer")))
{
streamToClient.writeObject(vector);
    streamToClient.writeObject(vctrList);
}
else if(msg.equals("LoginInfo"))
  {
  msg=streamFromClient.readLine();
int ver=verify(msg);
if(ver==1)
    {
String colon=new String(":");
int index=((String)msg).lastIndexOf(colon);
String userName=(String)msg.substring(0,index);
if(!(vctrList.indexOf((String)userName)>0))
{
streamToClient.writeObject("Welcome");
vctrList.addElement((String)userName);
}
}
else
{
streamToClient.writeObject("Login denied");
  }
} else if(msg.equals("RegisterInfo"))
{
msg=streamFromClient.readLine();
int ret=checkFile(msg);
if(ret==0)
streamToClient.writeObject("User Exists");
if(ret==1)
{
FileOutputStream out = new FileOutputStream("UsrPwd.txt",true);
PrintStream p = new PrintStream( out );
p.println();
                    p.println(msg);
p.close();
streamToClient.writeObject("Registered");
}
}
else if(msg.equals("User Logout"))
{
String remUser=streamFromClient.readLine();
boolean b=vctrList.removeElement((String)remUser);
}
else { message=message+msg;
vector.addElement((String)message);
    streamToClient.writeObject(vector); } }//end of try
    catch(Exception e)
{
System.out.println("Cannot get the client stream connect" + e);
}        finally
        {
         try
           {
           inFromClient.close();
           }
           catch(IOException e)
           {}
        } }//end of connect
}

解决方案 »

  1.   

    ----------------------
    //clientInt.java
    /**
    *soloist 
    */import java.io.*;
    import java.net.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.util.*;
    import javax.swing.Timer;public class clientInt extends JFrame implements ActionListener
    { Timer t = new Timer(5000,new TimerAction());
    String usr_name;
    public String remUser; class TimerAction implements ActionListener
    {
    Socket toServer;
    ObjectInputStream streamFromServer;
    PrintStream streamToServer;
    public void actionPerformed(ActionEvent e2)
    {       try
    {
             toServer=new Socket("jiangyu",1001);
             streamFromServer=new ObjectInputStream(toServer.getInputStream());
             streamToServer=new PrintStream(toServer.getOutputStream());
            message=txtMsg.getText(); //send a message to the server
            streamToServer.println("From Timer");

    //receive vectors from the server
            Vector vector=(Vector)streamFromServer.readObject();
    Vector vector1=(Vector)streamFromServer.readObject();

    //show the online users
    txtListUsers.setText("");
    for(int j=1;j<vector1.capacity();j++)
    {
                txtListUsers.append((String)vector1.elementAt(j));
        txtListUsers.append("\n");
        }

    //show the messsages
    int i=messageCount;
           for(;i<vector.capacity();i++)
    {
                txtMessages.append((String)vector.elementAt(i));
        txtMessages.append("\n");
    }
    messageCount=i;
    }//end of try

    catch(Exception e)
    {
    System.out.println("Exception "+e);
    } }//end of actionPerformed
    }//end of TimerListener class
    int messageCount=0;
    String name;
    PrintStream  streamToServer;
    ObjectInputStream streamFromServer;
    Socket toServer;
    JTextArea txtMessages;
    JTextArea txtListUsers;
    JTextField txtMsg;
    JButton msgSendBtn;
    JButton userLoginBtn;
    JButton userRegisterBtn;
    JButton userLogoutBtn;JLabel lblChatRoom;
    JLabel lblUserList;JScrollPane jspSendMsgPane;
    JScrollPane jspTxtMsgPane;
    JScrollPane jspUserListPane;JTextField textWriteMsg;
    String message;
    int nSend;
    public clientInt(String nm) //nm为登录用户名
    {
    remUser=nm;
    usr_name=nm;
    this.setTitle("聊天室---登录名: "+usr_name); //set the title name
        JPanel panel=new JPanel();  panel.setLayout(new GridBagLayout());
      GridBagConstraints gbCons=new GridBagConstraints(); gbCons.gridx=0;
    gbCons.gridy=0;
    lblChatRoom=new JLabel("聊天室",SwingConstants.LEFT);
    panel.add(lblChatRoom, gbCons); gbCons.gridx=1;
    gbCons.gridy=0; lblUserList=new JLabel("在线用户",SwingConstants.LEFT);
    panel.add(lblUserList, gbCons); gbCons.gridx=0;
    gbCons.gridy=1;
    gbCons.gridwidth=1;
    gbCons.gridheight=1;
    gbCons.weightx=1.0;
    gbCons.weighty=1.0;
    txtMessages=new JTextArea(25,35);
    txtMessages.setEditable(false);
    jspTxtMsgPane=new JScrollPane(txtMessages,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    panel.add(jspTxtMsgPane, gbCons); gbCons.gridx=1;
    gbCons.gridy=1;
    gbCons.gridwidth=1;
    gbCons.gridheight=1;
    gbCons.weightx=1.0;
    gbCons.weighty=1.0;
    txtListUsers=new JTextArea(25,10);
    txtListUsers.setEditable(false);
    jspUserListPane=new JScrollPane(txtListUsers,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    panel.add(jspUserListPane, gbCons); gbCons.gridx=0;
    gbCons.gridy=2;
    gbCons.gridwidth=1;
    gbCons.gridheight=1;
    gbCons.weightx=1.0;
    gbCons.weighty=1.0;
    txtMsg=new JTextField(35);
    jspSendMsgPane=new JScrollPane(txtMsg, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    panel.add(jspSendMsgPane, gbCons); gbCons.gridx=1;
    gbCons.gridy=2;
    gbCons.gridwidth=1;
    gbCons.gridheight=1;
    gbCons.weightx=1.0;
    gbCons.weighty=1.0;
    gbCons.anchor=GridBagConstraints.WEST;
    msgSendBtn=new JButton("发言");
    panel.add(msgSendBtn, gbCons); msgSendBtn.addActionListener(this); JPanel btnPanel=new JPanel(); userLogoutBtn=new JButton("退出");
    userLogoutBtn.addActionListener(this); //add a listerener to the window
    this.addWindowListener(
             new WindowAdapter()
     {
              public void windowClosing(WindowEvent e1)
    {
    try
    {
    Socket toServer;
    ObjectInputStream streamFromServer;
    PrintStream streamToServer;
             toServer=new Socket("jiangyu",1001);
          streamToServer=new PrintStream(toServer.getOutputStream());
             streamToServer.println("User Logout");
             streamToServer.println(remUser);
            }//end of try
    catch(Exception e2)
    {
    System.out.println("Exception Occured: "+e2);
    }
    }          }
            ); btnPanel.add(userLogoutBtn); gbCons.gridx=0;
    gbCons.gridy=3;
    gbCons.gridwidth=1;
    gbCons.gridheight=1;
    gbCons.weightx=1.0;
    gbCons.weighty=1.0;
    gbCons.anchor=GridBagConstraints.EAST;
    gbCons.fill=GridBagConstraints.HORIZONTAL;
    panel.add(btnPanel, gbCons); getContentPane().add(panel);    setDefaultCloseOperation(EXIT_ON_CLOSE); setLocation(150,100);
    setSize(546,567);
    setVisible(true);

    t.start();}//end of clientInt()
    public void actionPerformed(ActionEvent e1)
    {
    JButton button=(JButton)e1.getSource(); //if logout button clicked
    if(button.equals(userLogoutBtn))
    {
    try
    {
             toServer=new Socket("jiangyu",1001);
             streamToServer=new PrintStream(toServer.getOutputStream()); //send a msg to server for logging out
    streamToServer.println("User Logout");
             streamToServer.println(remUser);
            }
    catch(Exception e)
    {
    System.out.println("Exception Occured: "+e);
    }
    this.dispose();
    }
    //else if Send button is clicked
    else
    {
    int num1=0,num2=0,res=0;
    String name="";
    try
    {
             toServer=new Socket("jiangyu",1001);
             streamFromServer=new ObjectInputStream(toServer.getInputStream());
             streamToServer=new PrintStream(toServer.getOutputStream()); message=txtMsg.getText();
    String msg=message;

    //send the user name and msg typed to the server
    streamToServer.println(usr_name+":"+msg);

        txtMsg.setText("");

    //read the reply from the server
    Vector vector=(Vector)streamFromServer.readObject();
    int i=messageCount;
            for(;i<vector.capacity();i++)
    {
                txtMessages.append((String)vector.elementAt(i)); //display the messages
      txtMessages.append("\n");
            }//end of for
    messageCount=i;     }//end of try
    catch(Exception e)
    {
    System.out.println("Exception "+e);
    }
    }//end of else
    }//actionPerformed()
    public static void main(String args[])
    {
    String nm=new String();
    clientInt CI=new clientInt(nm);
    }
    }//end of class