我必须创建一个能够在服务器和客户端之间来回连续聊天的聊天应用程序。我有它,以便服务器和客户端可以一次发送一条消息,但我不知道如何编辑我的代码,以便您可以一次发送多条消息。此外,我需要能够在两台独立的计算机上运行它,我想我已准确地为此设置了代码,但我不确定。对此的验证和第一个问题的答案将不胜感激。我的每个班级的代码都在下面。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class ChatServer{
private ServerSocket serverSocket;
private Socket acceptSocket;
private PrintStream output;
private BufferedReader input;
private Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
ChatServer server = new ChatServer();
server.run();
}
public void run() {
try {
serverSocket = new ServerSocket(9999);
acceptSocket = serverSocket.accept();
output = new PrintStream(acceptSocket.getOutputStream());
input = new BufferedReader(new InputStreamReader(acceptSocket.getInputStream()));
while(acceptSocket.isConnected()) {
String message = input.readLine();
System.out.println(message);
String reply = scan.nextLine();
output.println(reply);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.Scanner;
public class ChatClient{
private Socket clientSocket;
private BufferedReader input;
private PrintStream output;
private Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
ChatClient client = new ChatClient();
client.run();
}
public void run() {
try {
clientSocket = new Socket("127.0.0.1", 9999);
output = new PrintStream(clientSocket.getOutputStream());
output.println("Connected to Server");
input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
while(clientSocket.isConnected()) {
String message = input.readLine();
System.out.println(message);
String reply = scan.nextLine();
output.println(reply);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:0)
SocketIO for Java是我的建议。它可以满足您的需求,最终可能会减少代码,并且文档上的文档非常精湛。甚至有一个Android应用程序演示使用它进行点对点聊天。