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 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
- ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
- ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
- ¥30 关于<main>标签页面跳转的问题
- ¥80 部署运行web自动化项目
- ¥15 腾讯云如何建立同一个项目中物模型之间的联系
- ¥30 VMware 云桌面水印如何添加
- ¥15 用ns3仿真出5G核心网网元
- ¥15 matlab答疑 关于海上风电的爬坡事件检测
- ¥88 python部署量化回测异常问题