1. Provide context: I have implemented a TCP client in C# within the context of Rhino (assuming it’s Rhino 3D software). The purpose is to receive messages from the client, but the code is not functioning as expected.i use python socket send some datas: like this:
b’{“status”: “new”, “co”: [[12.418717384338379, 0.0, 1.0326013565063477]], “pressure”: [0.9999979734420776]}’
2. in rhino grasshopper C# Relevant code: Here is the code snippet I am using:
private void RunScript(string HOST, int PORT, ref object datas)
{
string inhost = HOST;
int inport = PORT;
string result = “”;// 输出第一个消息 Component.Params.Output[1].AddVolatileData(new GH_Path(0, 1), 0, "one test"); // 创建一个新线程来运行TCP客户端代码 Thread thread = new Thread((obj) => { try { // 从传入的 Tuple 中获取主机地址和端口号 string threadHost = ((Tuple<string, int>) obj).Item1; int threadPort = ((Tuple<string, int>) obj).Item2; // 创建TcpClient并连接到服务器 TcpClient client = new TcpClient(); client.Connect(threadHost, threadPort); // 输出第二个消息 Component.Params.Output[1].AddVolatileData(new GH_Path(0, 1), 0, "TcpClient"); result = "连接TCP服务器" + threadHost + ":" + threadPort; // 打印连接成功的消息 Component.Params.Output[1].AddVolatileData(new GH_Path(0, 1), 0, result); Print(result); // 获取网络流 NetworkStream stream = client.GetStream(); // 读取数据 byte[] buffer = new byte[1024]; int bytesRead = stream.Read(buffer, 0, buffer.Length); string receivedData = Encoding.ASCII.GetString(buffer, 0, bytesRead); // 将接收到的数据输出到组件的第二个输出端口 Component.Params.Output[1].AddVolatileData(new GH_Path(1), 0, receivedData); // 关闭客户端连接 client.Close(); result += "\nSocket connection closed."; } catch (Exception e) { // 处理异常并打印错误消息 result = "Error: " + e.Message; Print(result); } }); // 启动新线程并传递参数,这将触发线程的执行 thread.Start(new Tuple<string, int>(inhost, inport));
}
- Expected output: I am expecting the code to receive messages from the client, similar to the following example, and output them:
this code can do Component.Params.Output[1].AddVolatileData(new GH_Path(1), 0, receivedData);
b’{“status”: “new”, “co”: [[12.418717384338379, 0.0, 1.0326013565063477]], “pressure”: [0.9999979734420776]}’
thanks!
c#socket.gh (12.3 KB)