所以我试图创建一个简单的Java聊天程序,要求用户输入要存储在服务器上的唯一用户名,然后其他客户端将使用该用户名发送消息。现在,用户名已正确存储并消息已正确发送到服务器。但是,我找不到将消息从服务器发送到其他客户端的方法。这是代码: 客户端向其他客户端发送消息的格式为用户名>>消息
服务器文件:
import java.util.List;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Stream;
public class server {
//List of client names and client handlers (capital)
private static List<String> clientNames = new ArrayList<String>();
private static List<Capital> clients = new ArrayList<Capital>();
public static boolean addName(String name) {
if(clientNames.contains(name))
return false;
else
clientNames.add(name);
return true;
}
public static void addClient (Capital c) {
clients.add(c);
}
public static String getMembers(){
return clientNames.toString();
}
//Send a message to another client
public static void directSend(String sender,String Receiver,String Message)
{
Stream <Capital> clientStream = clients.stream();
clientStream.forEach( client -> {
if(client.getName().equals(Receiver)) {
Socket socket = client.getSocket();
System.out.println(client.getName());
OutputStream os;
try {
os = socket.getOutputStream();
PrintWriter out = new PrintWriter(os, true);
out.println("From "+ sender+":"+ Message);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
public static void main(String[] args) throws Exception {
System.out.println("The server is running.");
ExecutorService pool = Executors.newFixedThreadPool(20);
int clientNumber = 0;
try (ServerSocket listener = new ServerSocket(6789)) {
while (true) {
pool.execute(new Capital(listener.accept(),
clientNumber++));
}
}
}
}
客户处理程序(称为Capital):
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class Capital implements Runnable {
private Socket socket;
private int clientNumber;
private String clientName;
//constants to define message types
private static final int JOIN = 1;
private static final int SEND = 2;
private static final int ACCEPTED = 3;
private static final int REJECTED = 4;
private static final int MEMBERS = 5;
public Capital(Socket socket, int clientNumber) {
this.socket = socket;
this.clientNumber = clientNumber;
System.out.println("New client #" + clientNumber + "connected at " + socket);
}
public String getName() {
return this.clientName;
}
public Socket getSocket() {
return this.socket;
}
public void run() {
try {
DataInputStream in = new DataInputStream(socket.getInputStream());
byte messageType = in.readByte();
BufferedReader inContent = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
String messageContent = inContent.readLine();
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
//handle each message type accordingly
switch(messageType) {
case JOIN:if(server.addName(messageContent)) {
out.write(ACCEPTED);
out.println("Welcome to the server "+messageContent);
this.clientName = messageContent;
server.addClient(this);
}
else {
out.write(REJECTED);
out.println("This name is already taken try again");
}
break;
case SEND: out.write(ACCEPTED);
String[] contentSplit = messageContent.split(" ");
String sender = contentSplit[0];
String Receiver = contentSplit[1];
String message = messageContent.substring(
messageContent.indexOf("#")+1);
server.directSend(sender, Receiver, message);
out.println("Message Sent");
break;
case MEMBERS:out.write(ACCEPTED);
out.println(server.getMembers());
break;
}
} catch (Exception e) {
System.out.println("Error handling client #" + clientNumber);
e.printStackTrace();
}
}
}
客户端文件:
import java.io.*;
public class MainClient {
private static boolean acceptFlag = true;
private static String acceptedName;
public static void setFlag(boolean result) {
acceptFlag = result;
}
public static void setName(String name) {
acceptedName = name;
}
public static void main(String[] args) throws Exception {
while(acceptFlag) {
System.out.print("Please Enter your name: ");
BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in));
String inputName = reader.readLine();
Client client = new Client(""+inputName);
client.join();
}
Client client = new Client(""+acceptedName);
System.out.println("Type Members any time to get "
+ "a list of available members");
client.run();
}
}
客户端实例
import java.io.*;
import java.net.*;
public class Client {
String sentence;
String modifiedSentence;
String name;
//constants to define message types
private static final int JOIN = 1;
private static final int SEND = 2;
private static final int ACCEPTED = 3;
private static final int MEMBERS = 5;
public Client(String name) {
this.name = name;
}
public void join() throws IOException {
this.sendMessage(this.name,JOIN,null,null);
}
public void sendMessage(String message,int type,String sender,String receiver)
throws IOException {
Socket clientSocket = new Socket("localhost",6789);
DataOutputStream outToServer =
new DataOutputStream(clientSocket.getOutputStream());
InputStream inputStream = clientSocket.getInputStream();
BufferedReader inFromServer =
new BufferedReader(new InputStreamReader(inputStream));
outToServer.writeByte(type);
if(sender!=null) {
outToServer.writeBytes(sender+" "+receiver+"#");
}
outToServer.writeBytes(message + '\n');
try {
if(inputStream.read()==ACCEPTED) {
MainClient.setFlag(false);
MainClient.setName(this.name);
}
else {
MainClient.setFlag(true);
}
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);}
catch(Exception e) {
System.out.println("Error sending the message,Try again");
}
finally {
clientSocket.close();
}
}
public void run() throws Exception {
boolean socketFlag = true;
while(socketFlag) {
System.out.print("Message:");
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
String inputMessage = inFromUser.readLine();
switch(inputMessage) {
case "Bye" : socketFlag=false;break;
case "Members" : this.sendMessage("",MEMBERS,null,null);break;
default: String receiver = inputMessage.split(">>")[0];
String message = inputMessage.substring(inputMessage.indexOf('>')+2);
this.sendMessage(message,SEND,this.name,receiver);
break;
}
}
}
}