gpt4 book ai didi

java - 在 Java 中多线程处理这个网络代码?

转载 作者:行者123 更新时间:2023-12-02 05:46:43 26 4
gpt4 key购买 nike

我正在尝试在 C-S 框架上构建一个聊天应用程序,但我还没有完全弄清楚如何对客户端代码进行多线程处理。如果有人能指出我正确的方向,我将不胜感激。

对于初学者来说,这段代码仅允许客户端和服务器进行双向通信:

我不会粘贴整个代码,只粘贴最重要的部分

服务器

// main
public static void main (String[] args) {
ChatServer cs = new ChatServer();
cs.runServer();
}

// run ChatServer
public void runServer() {
try {
server = new ServerSocket (12345, 100);

while (true) {
try {
waitForConnection(); // wait for connection
getStreams(); // get IO streams
processConnection(); // process connection
} catch (EOFException eofException) {
System.out.println("Server terminated connection");
} finally {
closeConnection(); // close connection
++counter;
}
}
} catch (IOException ioException) {
ioException.printStackTrace();
}
}

// wait for connection, and display connection info
private void waitForConnection() throws IOException {
System.out.println("Waiting for connection");
connection = server.accept();
System.out.println("Connection: " + counter + " received from: " +
connection.getInetAddress().getHostName());
}

// get streams to send and receive data
private void getStreams() throws IOException {
// set up output stream
output = new ObjectOutputStream(connection.getOutputStream());
output.flush(); // flush output buffer to send header information

// set up input stream
input = new ObjectInputStream(connection.getInputStream());

System.out.println("Got I/O streams");
}

private void processConnection() throws IOException {
String message = "Connection succesful";
sendData(message);

do { // process messages sent from client
try {
message = (String) input.readObject(); // read new message
System.out.println(message); // display message
} catch (ClassNotFoundException classNotFoundException) {
System.out.println("Unkonwn object type received!");
}
} while (!message.equals("CLIENT>>> TERMINATE"));
}

客户端

public static void main (String[] args) {
Client application;

// if no command line args
if (args.length == 0) {
application = new Client("127.0.0.1");
} else {
application = new Client(args[0]);
}
}

// connect to server and process messages from server
public void runClient() {
try {
connectToServer(); // create Socket to connect to server
getStreams(); // get input and output streams
processConnection(); // process connection
} catch (IOException ioException) {
ioException.printStackTrace();
} finally {
closeConnection();
}
}

// connect to server
private void connectToServer() throws IOException {
displayMessage("Attempting connection\n");

// create Socket to connect to server
client = new Socket(InetAddress.getByName(chatServer), 12345);

// dispaly connection information
displayMessage("Connected to: " + client.getInetAddress().getHostName());
}

// get streams to send and receive data
private void getStreams() throws IOException {
// set up output stream for objects
output = new ObjectOutputStream(client.getOutputStream());
output.flush();

// set up input stream for objects
input = new ObjectInputStream(client.getInputStream());

displayMessage("\nGot I/O streams\n");
}

// process connection with server
private void processConnection() throws IOException {
// enable enter field to send messages
setTextFieldEditable(true);

do {
try {
message = (String)input.readObject();
displayMessage("\n" + message);
} catch (ClassNotFoundException classNotFoundException) {
displayMessage("\nUnknown object type received!");
}
} while (!message.equals("SERVER>>> TERMINATE"));
}

// close streams and socket
private void closeConnection() {
displayMessage("\nClosing connection");
setTextFieldEditable(false);

try {
output.close();
input.close();
client.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}

我最初的想法:

  1. Client 类应该实现 runnable,但我不确定 run() 方法应该包含什么...

  2. Server 类 - 我感觉关键在 accept() 行,但我不确定如何继续...

我才开始学习 Java 中的多线程,但我们最近预计将构建这个多线程网络聊天应用程序,所以我有点不知道如何继续。

非常感谢任何有关此问题的指导,谢谢!

最佳答案

为了让这个答案简短,你基本上需要,

  1. 在实现Runnable的类中提取方法getStreams()processConnecion()。这些方法将在线程中运行
  2. waitForConnection()之后,构建新的Runnable类,注入(inject)您的connection(或Streams)和start()它<

多线程非常非常困难,Java 也不异常(exception)。在您的应用程序走得太远之前,请确保您完全了解Java Memory Model如何有效并遵循简单的规则:

  • 使变量尽可能不可变
  • 尽可能避免全局变量或实例变量
  • 不要重新发明轮子,使用(滥用) java.util.concurrent 中的类包
  • 不要在所有地方使用synchronized“以防万一”:您的应用会效率低下,并且可能在单个线程上运行得更好

作为多线程模型的替代方案,请使用Akka查看Actors。图书馆

关于java - 在 Java 中多线程处理这个网络代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23988506/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com