英文:
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("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) {
// 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("Welcome to the ChatRoom! Type to get started!");
}
request = scan.nextLine();
sender.println(request);
if (request.equals("quit")) {
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<ClientHandler> clients = new ArrayList<ClientHandler>();
public Server(int port) {
try {
serverSocket = new ServerSocket(port);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while (true) {
System.out.println("[SERVER] Waiting for Client Connection...");
try {
clientConnection = serverSocket.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("[SERVER] Client Connected Successfully!");
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<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) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void run() {
try {
while (true) {
String userInput = receiver.readLine();
if (userInput.equals("quit")) {
System.out.println("[SERVER] Received Forced User Shutdown Input. Now Exiting...");
System.exit(0);
break;
}
System.out.println("[SERVER] Received User Input... ");
sender = new PrintWriter(clientConnection.getOutputStream(), true);
System.out.println("[SERVER] Attempting to Send the Message to the Other Clients...");
for (ClientHandler aClient : clients) {
String serverResponse = "A user says: " + 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("\n" + 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("From: " + message.username + ": " + message.message_)
And you also have to use ObjectOutputStream y recomend you to investigate about sending objects trhough sockets
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论