【问题标题】:TCP Chat ServerTCP 聊天服务器
【发布时间】:2012-01-28 19:40:19
【问题描述】:

我正在修改我找到的关于如何创建接受多个客户端的 TCP 聊天服务器的教程。我最终也会创建一个客户端类,但到目前为止我正在使用 TELNET 对其进行测试。

我希望服务器不断检查输入,以便我可以使用关键字来执行服务器功能。因此,字符串单词“EXIT”断开客户端连接,字符串单词“Name:”打印“OK”。

这是我的想法,但它不起作用:

 public void run()  
    {
         String line;
         try    
         {
            while(true)   
            {
                if (input.readline("EXIT"))//Should close and remove client
                {
                    clients.remove(this);
                    users.remove(name);
                    break;
                }
                if(input.readline("Name:"))//Should print OK with username
                {
                    System.out.println("OK");
                }
                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()
 }

}

这是整个服务器类

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

  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)  
  {
        // 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 Bob's Chat Server!\n");
         // read name
         output.println("Please Enter a User Name: ");
         name  = input.readLine();
         users.add(name); // add to vector
         output.println("Welcome "+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)   
            {
                if (input.readline("EXIT"))
                {
                    clients.remove(this);
                    users.remove(name);
                    break;
                }
                if(input.readline(name))
                {
                    System.out.println("OK");
                }
                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

【问题讨论】:

  • 请扩展“不起作用”。编译错误?运行时错误?意想不到的功能? (您看到了什么,与您期望什么?)
  • 现在,这是我编译时得到的:TCPServer.java:79: 找不到符号符号:方法 readline(java.lang.String) 位置:类 java.io.BufferedReader if (input.readline("EXIT")) ^ TCPServer.java:85: 找不到符号符号:方法 readline(java.lang.String) 位置:类 java.io.BufferedReader if(input.readline("Name:" )) ^ 2 个错误
  • 您应该使用“WebSockets”来代替聊天服务器。这是现代的做法。
  • 我只是在学习教程。我对java和网络编程有点陌生。我只是想修改它以添加功能。我真的对 WebSockets 一无所知。

标签: java networking chat


【解决方案1】:

当输入行等于当前用户名时,如果不确切知道您要做什么,我认为这更符合您的要求:

    public void run(){
        try{
            while(true){
                String line = input.readLine();

                if("EXIT".equals(line)){
                    clients.remove(this);
                    users.remove(name);
                    break;
                }else if(name.equals(line)){
                    System.out.println("OK");
                }
                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()

这解决了几个问题:

  • input.readline 不是方法,但 input.readLine 是 - 并且它不接受任何参数。 (这应该显示为编译错误。)
  • 您从未为 line 字符串分配任何内容。
  • 您多次阅读该行。如果它与“EXIT”不匹配,则读取一个新行以与 name 进行比较 - 丢失用户为上一行输入的任何内容。

【讨论】:

  • 谢谢,这很有帮助。我试图使用 input.readLine 我想我打错了。
猜你喜欢
  • 2012-11-27
  • 2011-08-05
  • 2020-09-02
  • 1970-01-01
  • 2016-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多