【发布时间】:2016-02-12 09:37:51
【问题描述】:
我正在尝试创建一个简单的 Java 聊天应用程序,但遇到了一些问题。
下面是我的两个类的代码:
Serveur.java:
import java.io.*;
import java.net.*;
class Serveur{
private String msgClient, msgServeur;
private ServerSocket serverSocket;
private DataOutputStream out;
private Socket socket;
private int port;
private BufferedReader in;
public Serveur() throws IOException{
System.out.println("Serveur OK...");
this.port = 21;
this.serverSocket = new ServerSocket(this.port);
while(true){
this.socket = serverSocket.accept();
this.in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
this.out = new DataOutputStream(this.socket.getOutputStream());
this.msgClient = this.in.readLine();
System.out.println("Received: " + this.msgClient);
this.msgServeur = this.msgClient.toUpperCase() + '\n';
send(this.msgServeur);
}
}
public void send(String msg) throws IOException{
this.out.writeBytes(msg);
}
public static void main(String argv[]) throws Exception {
Serveur serveur = new Serveur();
}
}
Client.java:
import java.io.*;
import java.net.*;
class Client{
private String sentence;
private String modifiedSentence;
private int port;
private BufferedReader inUser;
private BufferedReader inServeur;
private Socket socket;
private DataOutputStream out;
public Client() throws UnknownHostException, IOException{
this.sentence = "";
this.modifiedSentence = "";
this.port = 21;
this.inUser = new BufferedReader(new InputStreamReader(System.in));
this.socket = new Socket("localhost", this.port);
this.out = new DataOutputStream(this.socket.getOutputStream());
this.inServeur = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
sentence = this.inUser.readLine();
this.out.writeBytes(sentence + '\n');
modifiedSentence = this.inServeur.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
this.socket.close();
}
public static void main(String argv[]) throws Exception{
Client client = new Client();
}
}
我有两个问题:
- 客户端发送消息,服务器返回相同的大写消息。如何允许客户端在不立即关闭其套接字连接的情况下发送消息?
- 服务器看起来不错,但是当我有多个客户端时,连接多个客户端会有什么变化吗?如何向特定客户端广播消息和消息?
【问题讨论】: