从同一行读取多个输入。

时间:2012-01-30 19:45:23

标签: java

我正在使用java中的一个简单的tcp聊天服务器。用户可以输入“push:”,“get”,“adios”,“help”等命令。 。 。我通过设置String Line = input.readLine()来检查这些用户命令(如下所示)。问题是当我输入“push:”时,我必须转到新行以获取新输入并将其分配给新字符串。我希望能够在用户键入命令后在同一行上获得输入。

例如:如果USER 1输入“push:”+“你好,你今天好吗?”我想存储“您好,今天好吗?”到一个数组,以便我以后可以打印它的内容。但是就像现在一样,我必须输入“push:”进入一个新行并输入“你好,今天你好吗?”将它存储到数组中。那太尴尬了。有没有办法将输入存储到同一行的两个不同的字符串?

这是我的服务器代码,请查看运行方法

// Chat Server runs at port no. 9020
import java.io.*;
import java.util.*;
import java.net.*;
import static java.lang.System.out;

public class  TCPServer 
{
  Vector<String> users = new Vector<String>();
  Vector<HandleClient> clients = new Vector<HandleClient>();
  Vector<String> Chat = new Vector<String>();

  int PORT = 9020;
  int NumClients = 10;

  public void process() throws Exception  
  {
      ServerSocket server = new ServerSocket(PORT,NumClients);
      out.println("Server Connected...");
      while(true) 
      {
         Socket client = server.accept();
         HandleClient c = new HandleClient(client);
         clients.add(c);
     }  // end of while
  }

  public static void main(String ... args) throws Exception 
  {
      new TCPServer().process();
  } // end of main

  public void boradcast(String user, String message)  
  {
        System.out.println(user + ": " + message);
        // send message to all connected users
        for (HandleClient c : clients)
           if (!c.getUserName().equals(user))
           {
              c.sendMessage(user,message);
           }
  }

  class HandleClient extends Thread 
  {
    String name = "";
    BufferedReader input;
    PrintWriter output;

    public HandleClient(Socket client) throws Exception 
    {
          // get input and output streams
         input = new BufferedReader(new InputStreamReader(client.getInputStream())) ;
         output = new PrintWriter (client.getOutputStream(),true);
         output.println("Welcome to Alan's Chat Server!\n");
         // read name
         output.println("Please Enter a User Name: ");
         name  = input.readLine();
         users.add(name); // add to vector
         output.println("\nWelcome "+name+" we hope you enjoy your chat today");
         start();
    }

    public void sendMessage(String uname,String  msg)  
    {
        output.println( uname + ": " + msg);
    }

    public String getUserName() 
    {  
        return name; 
    }

    public void run()  
    {
         String line;
         try    
         {
            while(true)   
            {
                        line = input.readLine();
            line.toLowerCase();//check this
                if("adios".equals(line))
            {
                output.println("\nClosing Connection  . . . Goodbye");
                            clients.remove(this);
                        users.remove(name);
                break;
                    }
            else if(name.equals(line))
            {
                            output.println("OK");
                    }
            else if("help".equals(line))
            {
                output.println("\nServer Commands:" + "\n\"audios:\" close the client connection\n"+
                                               "\"Name:\" display \"OK\"\n");//Check this
            }
            else if("push: ".equals(line))
            {
                String NewLine = input.readLine();
                Chat.add(NewLine);
                output.println("OK");
            }
            else if("get".equals(line))
            {
                output.println(Chat.toString());

            }
            else
            {
                    boradcast(name,line); // method  of outer class - send messages to all
            }
            }// end of while
         } // try
         catch(Exception e) 
         {
           System.out.println(e.getMessage());
         }
    } // end of run()
  } // end of inner class
} // end of Server

2 个答案:

答案 0 :(得分:1)

line = input.readLine();
line.toLowerCase();//check this
....
else if("push: ".equals(line))
.....

应该是

line = input.readLine();
String command = line.split(":")[0];
String otherStuff = line.split(":")[1];
command.toLowerCase();//check this
....
if("push".equals(command));
.....

答案 1 :(得分:1)

可能使用String.split("")或使用StringTokenizer

String line = input.read();
String [] d = s.split(":",2);

通过数组索引访问值;

修改

为了清楚起见,我在split方法中传递了2作为第二个参数,因为它限制了将数组拆分为两个索引,所以你没有3个这样的数组:

String.split("PUSH: I am hungry :P");因为它会输出[PUSH;我饿了; P]