我的代码 // 使用 FLTK 构建新的 GUI 实现 use fltk::{ app, button::Button, enums::{Color, FrameType},…
- User
我的代码 // 使用 FLTK 构建新的 GUI 实现 use fltk::{ app, button::Button, enums::{Color, FrameType}, frame::Frame, group::Pack, input::Input, input::IntInput, prelude::*, window::Window, }; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::rc::Rc; use std::cell::RefCell; use std::thread; use tokio::sync::mpsc::{UnboundedSender, unbounded_channel}; use tokio_stream::wrappers::UnboundedReceiverStream; use tokio_stream::StreamExt; use tokio::net::TcpStream; use tokio::io::{AsyncWriteExt, AsyncReadExt};
// 定义发送给网络线程的消息 enum NetworkCommand { Connect(String, u16), // 地址和端口 Send(String), // 发送的数据 Disconnect, }
// 定义从网络线程接收的消息 enum NetworkEvent { Connected, Disconnected, Received(String), Error(String), }
// 定义订单初始化消息 #[derive(Serialize, Deserialize, Debug, Clone)] struct OrderInitiateMessage { message_type: String, // "q" trp_str: u8, // 1-255 priority: u8, // 根据格式(a)或(b) code: Option, // 仅格式(b)使用 ikey: Option, // 仅格式(b)使用 parameters: Vec, // P0-P31 }
// 定义订单确认消息 #[derive(Serialize, Deserialize, Debug, Clone)] struct OrderAcknowledgeMessage { message_type: String, // "b" index: u16, trp_str: u8, status: u8, par_no: u8, spare: Option, ikey: Option, }
// 应用状态 struct AppState { orders: Vec, acknowledgements: Vec, status_map: HashMap<u8, String>, }
impl AppState { fn new() -> Self { let mut status_map = HashMap::new(); status_map.insert(0, "订单被拒绝".to_string()); status_map.insert(1, "订单已确认,加入队列".to_string()); // 根据规格继续添加状态映射
AppState { orders: Vec::new(), acknowledgements: Vec::new(), status_map, } }}
fn main() { let app = app::App::default(); let mut wind = Window::new(100, 100, 1000, 500, "测试应用"); // 增加窗口宽度以容纳更多布局
// 使用 Rc 和 RefCell 共享应用状态 let app_state = Rc::from(RefCell::from(AppState::new())); // 创建水平布局容器,分为左侧输入区和右侧显示区 let mut main_pack = Pack::new(10, 10, 980, 480, ""); main_pack.set_spacing(10); main_pack.set_type(fltk::group::PackType::Horizontal); // 左侧区域:输入和按钮 let mut input_pack = Pack::new(0, 0, 480, 480, ""); input_pack.set_spacing(10); input_pack.set_type(fltk::group::PackType::Vertical); // 添加连接参数输入字段 let mut address_input = Input::new(0, 0, 460, 30, "服务器地址:"); address_input.set_value("127.0.0.1"); let mut port_input = IntInput::new(0, 0, 460, 30, "端口:"); port_input.set_value("8080"); // 添加自定义参数输入字段 let mut msg_type_input = Input::new(0, 0, 460, 30, "消息类型:"); let mut trp_str_input = IntInput::new(0, 0, 460, 30, "Transport Structure:"); let mut priority_input = IntInput::new(0, 0, 460, 30, "优先级:"); let mut code_input = IntInput::new(0, 0, 460, 30, "代码 (可选):"); let mut ikey_input = IntInput::new(0, 0, 460, 30, "IKEY (可选):"); // 添加连接按钮 let mut connect_btn = Button::new(0, 0, 460, 40, "连接服务器"); connect_btn.set_color(Color::from_u32(0x1ABC9C)); // 添加发送按钮 let mut send_btn = Button::new(0, 0, 460, 40, "发送订单"); send_btn.set_color(Color::from_u32(0x28B463)); input_pack.end(); // 结束左侧输入布局 // 右侧区域:显示订单、确认消息和网络事件 let mut display_pack = Pack::new(0, 0, 480, 480, ""); display_pack.set_spacing(10); display_pack.set_type(fltk::group::PackType::Vertical); // 连接状态显示区域 let mut status_frame = Frame::new(0, 0, 480, 30, "连接状态: 未连接"); status_frame.set_frame(FrameType::FlatBox); status_frame.set_color(Color::from_u32(0xECF0F1)); // 当前的订单显示区域 let mut orders_frame = Frame::new(0, 0, 480, 150, "订单初始化消息"); orders_frame.set_frame(FrameType::DownBox); orders_frame.set_color(Color::White); // 当前的确认消息显示区域 let mut acks_frame = Frame::new(0, 0, 480, 150, "订单确认消息"); acks_frame.set_frame(FrameType::DownBox); acks_frame.set_color(Color::White); // 接收信息显示区域 let mut received_frame = Frame::new(0, 0, 480, 120, "接收信息"); received_frame.set_frame(FrameType::DownBox); received_frame.set_color(Color::White); display_pack.end(); // 结束右侧显示布局 main_pack.end(); // 结束主布局 wind.end(); wind.show(); // 创建跨线程通信通道,使用 tokio::sync::mpsc let (cmd_tx, cmd_rx) = unbounded_channel(); let (event_tx, event_rx) = unbounded_channel(); // 将接收端转换为 Stream let mut cmd_rx_stream = UnboundedReceiverStream::new(cmd_rx); let event_rx_stream = UnboundedReceiverStream::new(event_rx); // 启动网络线程 thread::spawn(move || { let rt = tokio::runtime::Runtime::new().unwrap(); rt.block_on(async move { let mut socket: Option<TcpStream> = None; loop { tokio::select! { Some(cmd) = cmd_rx_stream.next() => { match cmd { NetworkCommand::Connect(addr, port) => { match TcpStream::connect(format!("{}:{}", addr, port)).await { Ok(s) => { socket = Some(s); let _ = event_tx.send(NetworkEvent::Connected); }, Err(e) => { let _ = event_tx.send(NetworkEvent::Error(format!("连接失败: {}", e))); } } }, NetworkCommand::Send(data) => { if let Some(ref mut s) = socket { if let Err(e) = s.write_all(data.as_bytes()).await { let _ = event_tx.send(NetworkEvent::Error(format!("发送失败: {}", e))); } } else { let _ = event_tx.send(NetworkEvent::Error("尚未连接到服务器".to_string())); } }, NetworkCommand::Disconnect => { socket = None; let _ = event_tx.send(NetworkEvent::Disconnected); }, } }, // 这里可以添加接收服务器消息的逻辑,例如使用一个独立的任务来读取数据 _ = tokio::time::sleep(tokio::time::Duration::from_millis(100)) => { // 定期检查或其他逻辑 }, } // 如果有数据可以接收 if let Some(ref mut s) = socket { let mut buffer = [0u8; 1024]; match s.read(&mut buffer).await { Ok(0) => { // 连接关闭 socket = None; let _ = event_tx.send(NetworkEvent::Disconnected); }, Ok(n) => { let msg = String::from_utf8_lossy(&buffer[..n]).to_string(); let _ = event_tx.send(NetworkEvent::Received(msg)); }, Err(e) => { let _ = event_tx.send(NetworkEvent::Error(format!("接收失败: {}", e))); socket = None; } } } } }); }); // 添加连接按钮回调 { let cmd_tx = cmd_tx.clone(); let mut status_frame = status_frame.clone(); connect_btn.set_callback(move |_| { let address = address_input.value(); let port: u16 = match port_input.value().parse() { Ok(p) => p, Err(_) => { status_frame.set_label("连接状态: 端口号无效"); return; } }; cmd_tx.send(NetworkCommand::Connect(address, port)).unwrap(); }); } // 添加发送按钮回调 { let cmd_tx = cmd_tx.clone(); let msg_type_input = msg_type_input.clone(); let trp_str_input = trp_str_input.clone(); let priority_input = priority_input.clone(); let code_input = code_input.clone(); let ikey_input = ikey_input.clone(); let mut orders_frame = orders_frame.clone(); let mut received_frame = received_frame.clone(); send_btn.set_callback(move |_| { let message_type = msg_type_input.value(); let trp_str: u8 = trp_str_input.value().parse().unwrap_or(1); let priority: u8 = priority_input.value().parse().unwrap_or(1); let code = if code_input.value().is_empty() { None } else { Some(code_input.value().parse().unwrap_or(0)) }; let ikey = if ikey_input.value().is_empty() { None } else { Some(ikey_input.value().parse().unwrap_or(0)) }; let new_order = OrderInitiateMessage { message_type, trp_str, priority, code, ikey, parameters: vec![0; 32], // 可以根据需求调整 }; { let mut state = app_state.borrow_mut(); state.orders.push(new_order.clone()); } // 更新订单显示 let orders_text = { let state = app_state.borrow(); state.orders.iter().map(|o| { format!( "类型: {}\nTransport Structure: {}\nPriority: {}\nCode: {}\nIKEY: {}\nParameters: {:?}\n\n", o.message_type, o.trp_str, o.priority, o.code.unwrap_or(0), o.ikey.unwrap_or(0), o.parameters ) }).collect::<String>() }; orders_frame.set_label(&orders_text); // 构建发送命令 let send_command = if let Some(code) = new_order.code { format!("{},{},{},{},{}", new_order.message_type, new_order.trp_str, new_order.priority, code, new_order.ikey.unwrap_or(0)) } else { format!("{},{},{}", new_order.message_type, new_order.trp_str, new_order.priority) }; // 发送命令到网络线程 cmd_tx.send(NetworkCommand::Send(send_command)).unwrap(); }); } // 定期检查网络事件并更新 GUI { let event_rx_stream = event_rx_stream.clone(); let mut status_frame = status_frame.clone(); let mut acks_frame = acks_frame.clone(); let mut received_frame = received_frame.clone(); app::add_idle3(move |_| { while let Ok(Some(event)) = event_rx_stream.try_next() { match event { NetworkEvent::Connected => { status_frame.set_label("连接状态: 已连接"); status_frame.set_color(Color::from_u32(0x2ECC71)); }, NetworkEvent::Disconnected => { status_frame.set_label("连接状态: 已断开"); status_frame.set_color(Color::from_u32(0xE74C3C)); }, NetworkEvent::Received(msg) => { received_frame.set_label(&format!("接收信息:\n{}", msg)); }, NetworkEvent::Error(err) => { status_frame.set_label(&format!("连接状态: 错误 - {}", err)); status_frame.set_color(Color::from_u32(0xE74C3C)); }, } } }); } app.run().unwrap();}
报错
┌──(15821㉿DESKTOP-9JRLUKC)-[~/Documents/CODE/Autoder] 535ms └─$ cargo r Compiling test_project v0.1.0 (C:\Users\15821\Documents\CODE\Autoder) warning: unused import:
UnboundedSender--> src/main.rs:11:25 | 11 | use tokio::sync::mpsc::{UnboundedSender, unbounded_channel}; | ^^^^^^^^^^^^^^^ | = note:#[warn(unused_imports)]on by defaulterror[E0599]: no method named
clonefound for structUnboundedReceiverStreamin the current scope --> src/main.rs:307:47 | 307 | let event_rx_stream = event_rx_stream.clone(); | ^^^^^ | help: there is a methodclosewith a similar name | 307 | let event_rx_stream = event_rx_stream.close(); | ~~~~~For more information about this error, try
rustc --explain E0599. warning:test_project(bin "test_project") generated 1 warning error: could not compiletest_project(bin "test_project") due to 1 previous error; 1 warning emitted请指出错误并提供完整代码
- Assistant
The error occurs because you're trying to clone an instance of
UnboundedReceiverStream, which does not implement theClonetrait. Specifically, on line 307 of your code:let event_rx_stream = event_rx_stream.clone();The compiler error message:
error[E0599]: no method named `clone` found for struct `UnboundedReceiverStream` in the current scopeThis means that you cannot clone
event_rx_streamdirectly. To fix this, you should use an alternative approach to share the event stream with your GUI event loop.A common and effective solution is to use FLTK's own
SenderandReceiverfor inter-thread communication. The FLTKSenderis thread-safe and can send messages from other threads to the main GUI thread. Here's how you can modify your code:-
Use FLTK's channel for communication: Replace the
event_txandevent_rxchannel with FLTK'sapp::Senderandapp::Receiver. -
Send events via the FLTK
Sender: In your network thread, use the FLTKSenderto sendNetworkEventmessages back to the main thread. -
Process events in the GUI event loop: In the main thread, use the FLTK
Receiverto receive events and update the GUI accordingly.
Here's the corrected and complete code:
// 使用 FLTK 构建新的 GUI 实现 use fltk::{ app, button::Button, enums::{Color, FrameType}, frame::Frame, group::Pack, input::Input, input::IntInput, prelude::*, window::Window, }; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::rc::Rc; use std::cell::RefCell; use std::thread; use tokio::sync::mpsc::{unbounded_channel}; use tokio_stream::wrappers::UnboundedReceiverStream; use tokio_stream::StreamExt; use tokio::net::TcpStream; use tokio::io::{AsyncWriteExt, AsyncReadExt}; // 定义发送给网络线程的消息 enum NetworkCommand { Connect(String, u16), // 地址和端口 Send(String), // 发送的数据 Disconnect, } // 定义从网络线程接收的消息 #[derive(Clone)] enum NetworkEvent { Connected, Disconnected, Received(String), Error(String), } // 定义订单初始化消息 #[derive(Serialize, Deserialize, Debug, Clone)] struct OrderInitiateMessage { message_type: String, // "q" trp_str: u8, // 1-255 priority: u8, // 根据格式(a)或(b) code: Option<u16>, // 仅格式(b)使用 ikey: Option<u16>, // 仅格式(b)使用 parameters: Vec<u16>, // P0-P31 } // 定义订单确认消息 #[derive(Serialize, Deserialize, Debug, Clone)] struct OrderAcknowledgeMessage { message_type: String, // "b" index: u16, trp_str: u8, status: u8, par_no: u8, spare: Option<u8>, ikey: Option<u16>, } // 应用状态 struct AppState { orders: Vec<OrderInitiateMessage>, acknowledgements: Vec<OrderAcknowledgeMessage>, status_map: HashMap<u8, String>, } impl AppState { fn new() -> Self { let mut status_map = HashMap::new(); status_map.insert(0, "订单被拒绝".to_string()); status_map.insert(1, "订单已确认,加入队列".to_string()); // 根据规格继续添加状态映射 AppState { orders: Vec::new(), acknowledgements: Vec::new(), status_map, } } } fn main() { let app = app::App::default(); let mut wind = Window::new(100, 100, 1000, 500, "测试应用"); // 增加窗口宽度以容纳更多布局 // 使用 Rc 和 RefCell 共享应用状态 let app_state = Rc::from(RefCell::from(AppState::new())); // 创建水平布局容器,分为左侧输入区和右侧显示区 let mut main_pack = Pack::new(10, 10, 980, 480, ""); main_pack.set_spacing(10); main_pack.set_type(fltk::group::PackType::Horizontal); // 左侧区域:输入和按钮 let mut input_pack = Pack::new(0, 0, 480, 480, ""); input_pack.set_spacing(10); input_pack.set_type(fltk::group::PackType::Vertical); // 添加连接参数输入字段 let mut address_input = Input::new(0, 0, 460, 30, "服务器地址:"); address_input.set_value("127.0.0.1"); let mut port_input = IntInput::new(0, 0, 460, 30, "端口:"); port_input.set_value("8080"); // 添加自定义参数输入字段 let mut msg_type_input = Input::new(0, 0, 460, 30, "消息类型:"); let mut trp_str_input = IntInput::new(0, 0, 460, 30, "Transport Structure:"); let mut priority_input = IntInput::new(0, 0, 460, 30, "优先级:"); let mut code_input = IntInput::new(0, 0, 460, 30, "代码 (可选):"); let mut ikey_input = IntInput::new(0, 0, 460, 30, "IKEY (可选):"); // 添加连接按钮 let mut connect_btn = Button::new(0, 0, 460, 40, "连接服务器"); connect_btn.set_color(Color::from_u32(0x1ABC9C)); // 添加发送按钮 let mut send_btn = Button::new(0, 0, 460, 40, "发送订单"); send_btn.set_color(Color::from_u32(0x28B463)); input_pack.end(); // 结束左侧输入布局 // 右侧区域:显示订单、确认消息和网络事件 let mut display_pack = Pack::new(0, 0, 480, 480, ""); display_pack.set_spacing(10); display_pack.set_type(fltk::group::PackType::Vertical); // 连接状态显示区域 let mut status_frame = Frame::new(0, 0, 480, 30, "连接状态: 未连接"); status_frame.set_frame(FrameType::FlatBox); status_frame.set_color(Color::from_u32(0xECF0F1)); // 当前的订单显示区域 let mut orders_frame = Frame::new(0, 0, 480, 150, "订单初始化消息"); orders_frame.set_frame(FrameType::DownBox); orders_frame.set_color(Color::White); // 当前的确认消息显示区域 let mut acks_frame = Frame::new(0, 0, 480, 150, "订单确认消息"); acks_frame.set_frame(FrameType::DownBox); acks_frame.set_color(Color::White); // 接收信息显示区域 let mut received_frame = Frame::new(0, 0, 480, 120, "接收信息"); received_frame.set_frame(FrameType::DownBox); received_frame.set_color(Color::White); display_pack.end(); // 结束右侧显示布局 main_pack.end(); // 结束主布局 wind.end(); wind.show(); // 创建跨线程通信通道,使用 tokio::sync::mpsc let (cmd_tx, cmd_rx) = unbounded_channel(); // 使用 FLTK 的 Sender 和 Receiver let (s, r) = app::channel::<NetworkEvent>(); // 将接收端转换为 Stream let mut cmd_rx_stream = UnboundedReceiverStream::new(cmd_rx); // 启动网络线程 thread::spawn(move || { let s = s.clone(); let rt = tokio::runtime::Runtime::new().unwrap(); rt.block_on(async move { let mut socket: Option<TcpStream> = None; loop { tokio::select! { Some(cmd) = cmd_rx_stream.next() => { match cmd { NetworkCommand::Connect(addr, port) => { match TcpStream::connect(format!("{}:{}", addr, port)).await { Ok(sck) => { socket = Some(sck); s.send(NetworkEvent::Connected); }, Err(e) => { s.send(NetworkEvent::Error(format!("连接失败: {}", e))); } } }, NetworkCommand::Send(data) => { if let Some(ref mut sck) = socket { if let Err(e) = sck.write_all(data.as_bytes()).await { s.send(NetworkEvent::Error(format!("发送失败: {}", e))); } } else { s.send(NetworkEvent::Error("尚未连接到服务器".to_string())); } }, NetworkCommand::Disconnect => { socket = None; s.send(NetworkEvent::Disconnected); }, } }, // 定期检查或其他逻辑 _ = tokio::time::sleep(tokio::time::Duration::from_millis(100)) => { // 定期检查或其他逻辑 }, } // 如果有数据可以接收 if let Some(ref mut sck) = socket { let mut buffer = [0u8; 1024]; match sck.read(&mut buffer).await { Ok(0) => { // 连接关闭 socket = None; s.send(NetworkEvent::Disconnected); }, Ok(n) => { let msg = String::from_utf8_lossy(&buffer[..n]).to_string(); s.send(NetworkEvent::Received(msg)); }, Err(e) => { s.send(NetworkEvent::Error(format!("接收失败: {}", e))); socket = None; } } } } }); }); // 添加连接按钮回调 { let cmd_tx = cmd_tx.clone(); let mut status_frame = status_frame.clone(); connect_btn.set_callback(move |_| { let address = address_input.value(); let port: u16 = match port_input.value().parse() { Ok(p) => p, Err(_) => { status_frame.set_label("连接状态: 端口号无效"); return; } }; cmd_tx.send(NetworkCommand::Connect(address, port)).unwrap(); }); } // 添加发送按钮回调 { let cmd_tx = cmd_tx.clone(); let msg_type_input = msg_type_input.clone(); let trp_str_input = trp_str_input.clone(); let priority_input = priority_input.clone(); let code_input = code_input.clone(); let ikey_input = ikey_input.clone(); let mut orders_frame = orders_frame.clone(); let mut received_frame = received_frame.clone(); send_btn.set_callback(move |_| { let message_type = msg_type_input.value(); let trp_str: u8 = trp_str_input.value().parse().unwrap_or(1); let priority: u8 = priority_input.value().parse().unwrap_or(1); let code = if code_input.value().is_empty() { None } else { Some(code_input.value().parse().unwrap_or(0)) }; let ikey = if ikey_input.value().is_empty() { None } else { Some(ikey_input.value().parse().unwrap_or(0)) }; let new_order = OrderInitiateMessage { message_type, trp_str, priority, code, ikey, parameters: vec![0; 32], // 可以根据需求调整 }; { let mut state = app_state.borrow_mut(); state.orders.push(new_order.clone()); } // 更新订单显示 let orders_text = { let state = app_state.borrow(); state.orders.iter().map(|o| { format!( "类型: {}\nTransport Structure: {}\nPriority: {}\nCode: {}\nIKEY: {}\nParameters: {:?}\n\n", o.message_type, o.trp_str, o.priority, o.code.unwrap_or(0), o.ikey.unwrap_or(0), o.parameters ) }).collect::<String>() }; orders_frame.set_label(&orders_text); // 构建发送命令 let send_command = if let Some(code) = new_order.code { format!("{},{},{},{},{}", new_order.message_type, new_order.trp_str, new_order.priority, code, new_order.ikey.unwrap_or(0)) } else { format!("{},{},{}", new_order.message_type, new_order.trp_str, new_order.priority) }; // 发送命令到网络线程 cmd_tx.send(NetworkCommand::Send(send_command)).unwrap(); }); } // 定期检查网络事件并更新 GUI { let mut status_frame = status_frame.clone(); let mut acks_frame = acks_frame.clone(); let mut received_frame = received_frame.clone(); app::add_idle(move || { while let Some(event) = r.recv() { match event { NetworkEvent::Connected => { status_frame.set_label("连接状态: 已连接"); status_frame.set_color(Color::from_u32(0x2ECC71)); }, NetworkEvent::Disconnected => { status_frame.set_label("连接状态: 已断开"); status_frame.set_color(Color::from_u32(0xE74C3C)); }, NetworkEvent::Received(msg) => { received_frame.set_label(&format!("接收信息:\n{}", msg)); }, NetworkEvent::Error(err) => { status_frame.set_label(&format!("连接状态: 错误 - {}", err)); status_frame.set_color(Color::from_u32(0xE74C3C)); }, } } }); } app.run().unwrap(); }Explanation of the Changes:
-
Removed Cloning of
UnboundedReceiverStream: TheUnboundedReceiverStreamdoes not implement theClonetrait, so you cannot clone it. Instead, we use FLTK's channel mechanism for inter-thread communication. -
Using FLTK's
SenderandReceiver: We replaced theevent_txandevent_rxchannels with FLTK'sSender(s) andReceiver(r). This allows us to send messages from the network thread to the main GUI thread safely. -
Adjusted the Network Thread: In the network thread, we moved the
s(Sender) into the thread and used it to send events back to the main thread usings.send(event). -
Processing Events in the GUI Thread: Instead of trying to clone
event_rx_streamand use it in the GUI event loop, we use FLTK'sapp::add_idlemethod to periodically check theReceiver(r) for new events and update the GUI accordingly.
Key Points to Remember:
-
Do Not Clone Non-Clonable Types: If a type does not implement the
Clonetrait, you cannot clone it. Look for alternative ways to share or transfer ownership. -
Use Appropriate Inter-Thread Communication Mechanisms: When working with GUI frameworks like FLTK, it's often best to use their built-in mechanisms for inter-thread communication to ensure thread safety and compatibility with the event loop.
-
Be Mindful of Thread Safety and Lifetime: When moving variables into threads or closures, be mindful of their lifetimes and whether they implement
SendandSynctraits as needed.
After making these changes, your code should compile without the previous error, and the inter-thread communication should work as intended.
-