如何在多线程聊天客户端中为客户端分配用户名

huangapple go评论43阅读模式
英文:

How to give a username to clients in a multi-threaded chat client

问题

My Problem: 当前,我不明白如何为我的聊天客户端分配每个客户端的用户名。因此,我的输出只是:"A user says: [用户的聊天内容]"

My Code:

Client.java(自说明)

package chatroom;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class Client {

    public static void main(String[] args) {
        Client client = new Client("localhost", 9090);
    }

    private Socket clientConnection;
    private PrintWriter sender;
    private BufferedReader receiver;
    private Scanner scan = new Scanner(System.in);
    private String request;
    public static boolean firstMessage = true;

    public Client(String serverip, int port) {

        try {
            clientConnection = new Socket(serverip, port);
            sender = new PrintWriter(clientConnection.getOutputStream(), true);
            receiver = new BufferedReader(new InputStreamReader(clientConnection.getInputStream()));

        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        new Thread(new ChatHandler(clientConnection)).start();

        while (true) {
            if (request != null) {

            } else {
                System.out.println("欢迎来到聊天室!开始聊天吧!");
            }
                request = scan.nextLine();
                sender.println(request);
            if (request.equals("quit")) {
                System.exit(0);
                break;
            }
        }
    }
}

Server.java(自说明)

package chatroom;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

public class Server {

    public static void main(String[] args) {
        Server server = new Server(9090);
    }

    private ServerSocket serverSocket;
    private Socket clientConnection;
    private ArrayList<ClientHandler> clients = new ArrayList<ClientHandler>();

    public Server(int port) {
        try {
            serverSocket = new ServerSocket(port);
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        while (true) {
            System.out.println("[SERVER] 等待客户端连接...");
            try {
                clientConnection = serverSocket.accept();
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("[SERVER] 客户端连接成功!");
            ClientHandler clientThread = new ClientHandler(clientConnection, clients);
            clients.add(clientThread);
            Thread t = new Thread(clientThread);
            t.start();
        }
    }
}

ClientHandler.java(从用户接收输入并发送回客户端的可运行程序)

package chatroom;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;

public class ClientHandler implements Runnable {

    private Socket clientConnection;
    private BufferedReader receiver;
    private PrintWriter sender;
    private String clientRequest, clientUsername;
    private ArrayList<ClientHandler> clients;

    public ClientHandler(Socket clientConnection, ArrayList<ClientHandler> clients) {
        this.clientConnection = clientConnection;
        this.clients = clients;

        try {
            receiver = new BufferedReader(new InputStreamReader(clientConnection.getInputStream()));
            sender = new PrintWriter(clientConnection.getOutputStream(), true);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        try {
            while (true) {
                String userInput = receiver.readLine();
                if (userInput.equals("quit")) {
                    System.out.println("[SERVER] 收到强制用户关闭输入。现在退出...");
                    System.exit(0);
                    break;
                }

                System.out.println("[SERVER] 收到用户输入...");

                sender = new PrintWriter(clientConnection.getOutputStream(), true);
                System.out.println("[SERVER] 正在尝试将消息发送给其他客户端...");

                for (ClientHandler aClient : clients) {

                    String serverResponse = "一个用户说:" + userInput;
                    aClient.sender.println(serverResponse);

                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

ChatHandler.java(向客户端输出聊天内容,允许客户端在产生输出时进行输入)

package chatroom;

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

public class ChatHandler implements Runnable {

    private Socket clientConnection;
    private BufferedReader receiver;

    public ChatHandler(Socket clientConnection) {
        this.clientConnection = clientConnection;
        try {
            receiver = new BufferedReader(new InputStreamReader(clientConnection.getInputStream()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        try {
            while (true) {
                String serverResponse = receiver.readLine();

                if (serverResponse == null) {
                    break;
                }

                System.out.println("\n" + serverResponse);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
英文:

My Problem: Currently, I do not understand how to assign each Client a username for my chat client. Therefore, I just have the output as: "A user says: [user's chat]"

My Code:

Client.java (Self Explanatory)

package chatroom;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Client {
public static void main(String[] args) {
Client client = new Client(&quot;localhost&quot;, 9090);
}
private Socket clientConnection;
private PrintWriter sender;
private BufferedReader receiver;
private Scanner scan = new Scanner(System.in);
private String request;
public static boolean firstMessage = true;
public Client(String serverip, int port) {
try {
clientConnection = new Socket(serverip, port);
sender = new PrintWriter(clientConnection.getOutputStream(), true);
receiver = new BufferedReader(new InputStreamReader(clientConnection.getInputStream()));
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new Thread(new ChatHandler(clientConnection)).start();
while (true) {
if (request != null) {
} else {
System.out.println(&quot;Welcome to the ChatRoom! Type to get started!&quot;);
}
request = scan.nextLine();
sender.println(request);
if (request.equals(&quot;quit&quot;)) {
System.exit(0);
break;
}
}
}
}

Server.java (Self Explanatory)

package chatroom;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class Server {
public static void main(String[] args) {
Server server = new Server(9090);
}
private ServerSocket serverSocket;
private Socket clientConnection;
private ArrayList&lt;ClientHandler&gt; clients = new ArrayList&lt;ClientHandler&gt;();
public Server(int port) {
try {
serverSocket = new ServerSocket(port);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while (true) {
System.out.println(&quot;[SERVER] Waiting for Client Connection...&quot;);
try {
clientConnection = serverSocket.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(&quot;[SERVER] Client Connected Successfully!&quot;);
ClientHandler clientThread = new ClientHandler(clientConnection, clients);
clients.add(clientThread);
Thread t = new Thread(clientThread);
t.start();
}
}
}

ClientHandler.java (Runnable that receieves input from user and sends it back to clients)

package chatroom;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
public class ClientHandler implements Runnable {
private Socket clientConnection;
private BufferedReader receiver;
private PrintWriter sender;
private String clientRequest, clientUsername;
private ArrayList&lt;ClientHandler&gt; clients;
public ClientHandler(Socket clientConnection, ArrayList&lt;ClientHandler&gt; clients) {
this.clientConnection = clientConnection;
this.clients = clients;
try {
receiver = new BufferedReader(new InputStreamReader(clientConnection.getInputStream()));
sender = new PrintWriter(clientConnection.getOutputStream(), true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void run() {
try {
while (true) {
String userInput = receiver.readLine();
if (userInput.equals(&quot;quit&quot;)) {
System.out.println(&quot;[SERVER] Received Forced User Shutdown Input. Now Exiting...&quot;);
System.exit(0);
break;
}
System.out.println(&quot;[SERVER] Received User Input... &quot;);
sender = new PrintWriter(clientConnection.getOutputStream(), true);
System.out.println(&quot;[SERVER] Attempting to Send the Message to the Other Clients...&quot;);
for (ClientHandler aClient : clients) {
String serverResponse = &quot;A user says: &quot; + userInput;
aClient.sender.println(serverResponse);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} 
}
}

ChatHandler.java (Runnable that outputs the chat to the client which allows the client to type while output is being produced)

package chatroom;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
public class ChatHandler implements Runnable{
private Socket clientConnection;
private BufferedReader receiver;
public ChatHandler(Socket clientConnection) {
this.clientConnection = clientConnection;
try {
receiver = new BufferedReader(new InputStreamReader(clientConnection.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void run() {
try {
while(true) {
String serverResponse = receiver.readLine();
if(serverResponse == null) {
break;
}
System.out.println(&quot;\n&quot; + serverResponse);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Any help is appreciated! Thank you all so much!
~AbysssCoder

答案1

得分: 1

以下是翻译好的代码部分:

发送文本和用户名的一种方法是创建一个新的对象

可以像这样

public class Message() implements Serializable {
     public String message_, username;
     private static final long serialVersionUID = 1L;

     public Message(String message, String Username){
         this.message_ = message;
         this.username = Username;
     }
}

然后不使用普通的 DataInputStream而是使用 ObjectInputStream 来发送对象
像这样

DataInputStream in = new DataInputStram(socket.getInputStream);
ObjectInputStream input = new ObjectInputSream(in);

Message message = (Message) input.readObject;
System.out.println("From: " + message.username + ": " + message.message_);

并且你还必须使用 ObjectOutputStream我建议你研究一下如何通过套接字发送对象
英文:

A way that you can send the text and username is creating a new Object

It can be something like this:

public class Message() implements Serializable {
public String message_, username;
private static final long serialVersionUID = 1L;
public Message(String message, String Username){
this.message_ = message;
this.username = Username
}
}

Then instead of using the normal DataInputStream you use ObjectInputStream to send the object.
like this

  DataInputStream in = new DataInputStram(socket.getInputStream);
ObjectInputStream input = new ObjectInputSream(in);
Message message = (Message) input.readObject;
System.out.println(&quot;From: &quot; + message.username + &quot;: &quot; + message.message_)

And you also have to use ObjectOutputStream y recomend you to investigate about sending objects trhough sockets

huangapple
  • 本文由 发表于 2020年10月13日 11:11:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/64327923.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定