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 对于知识的学以致用的解释
- ¥50 三种调度算法报错 有实例
- ¥15 关于#python#的问题,请各位专家解答!
- ¥200 询问:python实现大地主题正反算的程序设计,有偿
- ¥15 smptlib使用465端口发送邮件失败
- ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
- ¥15 对于squad数据集的基于bert模型的微调
- ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
- ¥20 steam下载游戏占用内存
- ¥15 CST保存项目时失败