Java聊天服务器

发布于 2024-08-08 06:56:59 字数 6582 浏览 2 评论 0原文

仅供参考,这是家庭作业。我必须构建一个 Java 聊天服务器。我已经能够构建一个与 1 个客户端通信的服务器。但我需要它来与多个用户进行通信。

用户应该输入他们想要交谈的人的名字,然后是破折号(-),然后是要发送的消息。我能够让用户登录,但无法打印用户列表或发送给其他用户的消息。这是服务器代码:

/** 
    Threaded Server
*/

import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Set;

public class ThreadedServer
{
    public static void main( String[] args) throws Exception
    {
        HashMap<String, Socket> users = new HashMap<String, Socket>( );
        ServerSocket server = new ServerSocket(5679);
        System.out.println( "THE CHAT SERVER HAS STARTED! =)" );
        while(true)
        {
            Socket client = server.accept();
            ThreadedServer ser = new ThreadedServer();
            ClientFromThread cft =ser.new ClientFromThread(client);
            String name = cft.getUserName();
            users.put( name, client );
            cft.giveUsersMap( users );
            //cft.giveOnlineUsers( ); //DOES NOT WORK YET!!!!
            System.out.println("Threaded server connected to " 
                        + client.getInetAddress() + "  USER: " + name );            
        } 

    }

    //***************************************************************************************************

    class ClientFromThread extends Thread
    {
        private Socket client;
        private Scanner fromClient;
        private PrintWriter toClient;
        private String userName;
        HashMap<String, Socket> users;

        public ClientFromThread( Socket c ) throws Exception
        {
            client = c;
            fromClient = new Scanner( client.getInputStream() );
            toClient = new PrintWriter( client.getOutputStream(), true );
            userName = getUser();
            start();
        }
        public void giveUsersMap( HashMap<String, Socket> users )
        {
            this.users = users;
        }

        //THIS DOESNT WORK YET... IT PRINTS THE FIRST LINE BUT NOT THE LIST
        public void giveOnlineUsers()
        {
            toClient.println("These users are currently online:");
            Set<String> userList = users.keySet();
            String[] userNames = null;
            userList.toArray( userNames );

            for( int i = 0; i< userNames.length; i++ )
            {
                toClient.println(userNames[i]);
            }
        }

        public String getUserName()
        {
            return userName;
        }

        private String getUser()
        {
            String s = "";
            while( (s.length() < 1) || (s == null) )
            {
                toClient.println("What is your first name? ");
                s=fromClient.nextLine().trim();
            }
            toClient.println("Thank You! Welcome to the chat room " + s + ".");
            return s.toUpperCase();
        }

        public void run() 
        {
            String s = null;
            String toUser;
            String mesg;

            while( (s=fromClient.nextLine().trim()) != null )
            {
                if( s.equalsIgnoreCase( "END" )) break;

                for( int i=0; i<s.length(); i++)
                {
                    if( s.charAt(i) == '-' )
                    {
                        toUser = s.substring( 0, i ).trim().toUpperCase();
                        mesg = s.substring( i+1 ).trim();
                        Socket client = users.get( toUser );
                        try
                        {
                            ClientToThread ctt = new ClientToThread(client);
                            ctt.sendMesg( mesg, toUser );
                            ctt.start();
                        }
                        catch(Exception e){e.printStackTrace();}
                        break;
                    }
                    if( (i+1) == s.length() )
                    {
                        toClient.println("Sorry the text was invalid. Please enter a user name " +
                                                     "followed by a dash (-) then your message.");
                    }
                }
            }
            try
            {
                fromClient.close();
                toClient.close();
                client.close();
            }
            catch(Exception e){e.printStackTrace();}
        }

    } //end class ClientFromThread

    //***************************************************************************************************

    class ClientToThread extends Thread
    {
        private Socket client;
        private PrintWriter toClient;
        private String mesg;

        public ClientToThread( Socket c ) throws Exception
        {
            client = c;
            toClient = new PrintWriter( client.getOutputStream(), true );
        }

        public void sendMesg( String mesg, String userName )
        {
            this.mesg = userName + ": " + mesg;
        }
        public void run() 
        {
            toClient.println(mesg);

            try
            {
                toClient.close();
                client.close();
            }
            catch(Exception e){e.printStackTrace();}
        }

    } //end class ClientToThread

    //***************************************************************************************************

} //end class ThreadedServer

这是客户端代码”

import java.net.Socket;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;


public class ReverseClient 
{
public static void main( String[] args ) throws Exception
{
    String line = null;
    Socket server= new Socket( "10.0.2.103", 5679);
    System.out.println( "Connected to host: " + server.getInetAddress() );
    BufferedReader fromServer = new BufferedReader(
                new InputStreamReader(server.getInputStream()) );
    PrintWriter toServer = new PrintWriter( server.getOutputStream(), true );
    BufferedReader input = new BufferedReader( 
                new InputStreamReader(System.in) );
    while( (line=input.readLine()) !=null )
    {
        toServer.println(line);
        System.out.println( fromServer.readLine() );
    }
    fromServer.close();
    toServer.close();
    input.close();
    server.close();

}   
}

这是控制台输出(顶部是服务器,底部是客户端): 替代文本

我收到错误(如上图所示)并且消息未发送。关于如何处理这些问题有什么建议吗?

FYI This is homework. I have to build a Java Chat server. I have been able to build a server which communicates with 1 client. But I need this to communicate with multiple users.

A user is supposed to type in the person's name they wish to talk to followed by a dash (-) and then the message to be sent. I am able to get users signed on but I am not able to get the list of users to print out or the messages to send to other users. Here is the server code:

/** 
    Threaded Server
*/

import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Set;

public class ThreadedServer
{
    public static void main( String[] args) throws Exception
    {
        HashMap<String, Socket> users = new HashMap<String, Socket>( );
        ServerSocket server = new ServerSocket(5679);
        System.out.println( "THE CHAT SERVER HAS STARTED! =)" );
        while(true)
        {
            Socket client = server.accept();
            ThreadedServer ser = new ThreadedServer();
            ClientFromThread cft =ser.new ClientFromThread(client);
            String name = cft.getUserName();
            users.put( name, client );
            cft.giveUsersMap( users );
            //cft.giveOnlineUsers( ); //DOES NOT WORK YET!!!!
            System.out.println("Threaded server connected to " 
                        + client.getInetAddress() + "  USER: " + name );            
        } 

    }

    //***************************************************************************************************

    class ClientFromThread extends Thread
    {
        private Socket client;
        private Scanner fromClient;
        private PrintWriter toClient;
        private String userName;
        HashMap<String, Socket> users;

        public ClientFromThread( Socket c ) throws Exception
        {
            client = c;
            fromClient = new Scanner( client.getInputStream() );
            toClient = new PrintWriter( client.getOutputStream(), true );
            userName = getUser();
            start();
        }
        public void giveUsersMap( HashMap<String, Socket> users )
        {
            this.users = users;
        }

        //THIS DOESNT WORK YET... IT PRINTS THE FIRST LINE BUT NOT THE LIST
        public void giveOnlineUsers()
        {
            toClient.println("These users are currently online:");
            Set<String> userList = users.keySet();
            String[] userNames = null;
            userList.toArray( userNames );

            for( int i = 0; i< userNames.length; i++ )
            {
                toClient.println(userNames[i]);
            }
        }

        public String getUserName()
        {
            return userName;
        }

        private String getUser()
        {
            String s = "";
            while( (s.length() < 1) || (s == null) )
            {
                toClient.println("What is your first name? ");
                s=fromClient.nextLine().trim();
            }
            toClient.println("Thank You! Welcome to the chat room " + s + ".");
            return s.toUpperCase();
        }

        public void run() 
        {
            String s = null;
            String toUser;
            String mesg;

            while( (s=fromClient.nextLine().trim()) != null )
            {
                if( s.equalsIgnoreCase( "END" )) break;

                for( int i=0; i<s.length(); i++)
                {
                    if( s.charAt(i) == '-' )
                    {
                        toUser = s.substring( 0, i ).trim().toUpperCase();
                        mesg = s.substring( i+1 ).trim();
                        Socket client = users.get( toUser );
                        try
                        {
                            ClientToThread ctt = new ClientToThread(client);
                            ctt.sendMesg( mesg, toUser );
                            ctt.start();
                        }
                        catch(Exception e){e.printStackTrace();}
                        break;
                    }
                    if( (i+1) == s.length() )
                    {
                        toClient.println("Sorry the text was invalid. Please enter a user name " +
                                                     "followed by a dash (-) then your message.");
                    }
                }
            }
            try
            {
                fromClient.close();
                toClient.close();
                client.close();
            }
            catch(Exception e){e.printStackTrace();}
        }

    } //end class ClientFromThread

    //***************************************************************************************************

    class ClientToThread extends Thread
    {
        private Socket client;
        private PrintWriter toClient;
        private String mesg;

        public ClientToThread( Socket c ) throws Exception
        {
            client = c;
            toClient = new PrintWriter( client.getOutputStream(), true );
        }

        public void sendMesg( String mesg, String userName )
        {
            this.mesg = userName + ": " + mesg;
        }
        public void run() 
        {
            toClient.println(mesg);

            try
            {
                toClient.close();
                client.close();
            }
            catch(Exception e){e.printStackTrace();}
        }

    } //end class ClientToThread

    //***************************************************************************************************

} //end class ThreadedServer

Here is the Client code"

import java.net.Socket;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;


public class ReverseClient 
{
public static void main( String[] args ) throws Exception
{
    String line = null;
    Socket server= new Socket( "10.0.2.103", 5679);
    System.out.println( "Connected to host: " + server.getInetAddress() );
    BufferedReader fromServer = new BufferedReader(
                new InputStreamReader(server.getInputStream()) );
    PrintWriter toServer = new PrintWriter( server.getOutputStream(), true );
    BufferedReader input = new BufferedReader( 
                new InputStreamReader(System.in) );
    while( (line=input.readLine()) !=null )
    {
        toServer.println(line);
        System.out.println( fromServer.readLine() );
    }
    fromServer.close();
    toServer.close();
    input.close();
    server.close();

}   
}

Here is the console output (the top is the server, bottom is the client):
alt text

I am getting errors (as shown in the image above) and the messages are not sending. Any suggestions on how to take care of these issues?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

GRAY°灰色天空 2024-08-15 06:56:59

到目前为止,我发现这是一个问题,但我不认为这是唯一的问题。

这将有助于 NoSuchElementException
在第 90 行左右,将此...更改

while( (s=fromClient.nextLine().trim()) != null )
{

为此...

while(fromClient.hasNext())
{
   s = fromClient.nextLine().trim();

好的,刚刚在 ClientToThread.run() 中发现了另一个问题...发送第一条消息后,您将关闭客户端连接。我把它们都注释掉了,看起来效果更好了一些。

public void run()
  {
     toClient.println(mesg);
     try {
        //toClient.close();
        //client.close();
     }
     catch (Exception e)  {
        e.printStackTrace();
     }
  }

So far I found this to be a problem, but I don't think this is the only problem..

This will help the NoSuchElementException
On around line 90 Change this...

while( (s=fromClient.nextLine().trim()) != null )
{

to this...

while(fromClient.hasNext())
{
   s = fromClient.nextLine().trim();

OK just found another problem in ClientToThread.run()... You are closing the client connections after you send the first message. I commented them both out and it seems to be working a little better.

public void run()
  {
     toClient.println(mesg);
     try {
        //toClient.close();
        //client.close();
     }
     catch (Exception e)  {
        e.printStackTrace();
     }
  }
你是年少的欢喜 2024-08-15 06:56:59

您的第一个问题是解析来自用户的消息。

您循环遍历该字符串,它有两个选项之一:字符是破折号或无效。

因此,理想情况下,您应该收到一条关于用户名中破折号之前的字符数的无效消息。

您应该使用 String.indexOf 来确定破折号的位置,然后将消息分成两部分,如果 indexOf 的结果是 -1 则它是无效消息。

Your first problem is with the parsing of the message from the user.

You loop through the string, and it has one of two options, either the character is a dash or it is invalid.

So, ideally, you should be getting an invalid message for the number of a characters in the username before the dash.

You should use String.indexOf to determine where the dash is, and then split the message into it's two parts, and if the result of indexOf is -1 then it is an invalid message.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文