java服务端 和C#客户端 通过Socket和Json序列化互传对象,可以互传hashmap对象吗?如果可以请发下socket的代码,谢谢
7条回答 默认 最新
- Leodong. 2023-03-23 16:30关注
该回答引用GPTᴼᴾᴱᴺᴬᴵ以及结合自己思路,具体如下:
是可以通过Socket和Json序列化互传HashMap对象。以下是Java服务端和C#客户端的示例代码:
1、Java服务端代码:import java.io.*; import java.net.*; import java.util.HashMap; import com.google.gson.Gson; public class Server { private static final int PORT = 8888; public static void main(String[] args) { try { ServerSocket serverSocket = new ServerSocket(PORT); System.out.println("Server started."); while (true) { Socket socket = serverSocket.accept(); System.out.println("Client connected."); // Read the HashMap object from the client InputStream is = socket.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String json = br.readLine(); Gson gson = new Gson(); HashMap<String, String> hashMap = gson.fromJson(json, HashMap.class); System.out.println("Received HashMap from client: " + hashMap.toString()); // Send the HashMap object back to the client OutputStream os = socket.getOutputStream(); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os)); bw.write(gson.toJson(hashMap)); bw.newLine(); bw.flush(); socket.close(); } } catch (IOException e) { e.printStackTrace(); } } }
2、C#客户端代码:
using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Text; using System.Collections.Generic; using Newtonsoft.Json; class Client { static void Main(string[] args) { try { TcpClient tcpClient = new TcpClient("localhost", 8888); Console.WriteLine("Connected to server."); // Send a HashMap object to the server NetworkStream ns = tcpClient.GetStream(); Dictionary<string, string> hashMap = new Dictionary<string, string>(); hashMap.Add("name", "John"); hashMap.Add("age", "30"); string json = JsonConvert.SerializeObject(hashMap); byte[] bytesToSend = Encoding.UTF8.GetBytes(json); ns.Write(bytesToSend, 0, bytesToSend.Length); ns.Flush(); Console.WriteLine("Sent HashMap to server: " + json); // Receive the HashMap object from the server byte[] bytesToRead = new byte[tcpClient.ReceiveBufferSize]; int bytesRead = ns.Read(bytesToRead, 0, tcpClient.ReceiveBufferSize); string receivedJson = Encoding.UTF8.GetString(bytesToRead, 0, bytesRead); Dictionary<string, string> receivedHashMap = JsonConvert.DeserializeObject<Dictionary<string, string>>(receivedJson); Console.WriteLine("Received HashMap from server: " + receivedJson); tcpClient.Close(); } catch (Exception e) { Console.WriteLine("Exception: " + e.ToString()); } } }
如果以上回答对您有所帮助,望采纳~谢谢
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 怎么让数码管亮的同时让led执行流水灯代码
- ¥20 SAP HANA SQL Script 。如何判断字段值包含某个字符串
- ¥85 cmd批处理参数如果含有双引号,该如何传入?
- ¥15 fx2n系列plc的自控成型机模拟
- ¥15 时间序列LSTM模型归回预测代码问题
- ¥50 使用CUDA如何高效的做并行化处理,是否可以多个分段同时进行匹配计算处理?目前数据传输速度有些慢,如何提高速度,使用gdrcopy是否可行?请给出具体意见。
- ¥15 基于STM32,电机驱动模块为L298N,四路运放电磁传感器,三轮智能小车电磁组电磁循迹(两个电机,一个万向轮),如何通过环岛的原理及完整代码
- ¥20 机器学习或深度学习问题?困扰了我一个世纪,晚来天欲雪,能饮一杯无?
- ¥15 c语言数据结构高铁订票系统
- ¥15 关于wkernell.PDB加载的问题,如何解决?(语言-c#|开发工具-vscode)