java 和C# 通过Socket 可以互传hashmap对象吗?

java服务端 和C#客户端 通过Socket和Json序列化互传对象,可以互传hashmap对象吗?如果可以请发下socket的代码,谢谢

该回答引用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());
        }
    }
}

如果以上回答对您有所帮助,望采纳~谢谢

参考GPT:是的,Java和C#通过Socket和Json序列化可以互传HashMap对象。

以下是Java服务器端代码示例:

import java.io.*;
import java.net.*;
import java.util.HashMap;
import com.google.gson.Gson;

public class Server {
    public static void main(String[] args) throws Exception {
        ServerSocket serverSocket = new ServerSocket(1234);
        System.out.println("Server started");

        while (true) {
            Socket socket = serverSocket.accept();
            System.out.println("Client connected");

            // create a HashMap to send to the client
            HashMap<String, Integer> hashMap = new HashMap<String, Integer>();
            hashMap.put("one", 1);
            hashMap.put("two", 2);
            hashMap.put("three", 3);

            // create a JSON string from the HashMap
            Gson gson = new Gson();
            String jsonString = gson.toJson(hashMap);

            // send the JSON string to the client
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            out.println(jsonString);

            // close the socket
            socket.close();
            System.out.println("Client disconnected");
        }
    }
}

以下是C#客户端代码示例:

using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Sockets;
using Newtonsoft.Json;

class Client {
    static void Main() {
        TcpClient client = new TcpClient("localhost", 1234);
        Console.WriteLine("Connected to server");

        // receive the JSON string from the server
        StreamReader reader = new StreamReader(client.GetStream());
        string jsonString = reader.ReadLine();

        // deserialize the JSON string into a HashMap
        Dictionary<string, int> hashMap = JsonConvert.DeserializeObject<Dictionary<string, int>>(jsonString);

        // print the HashMap
        foreach (KeyValuePair<string, int> entry in hashMap) {
            Console.WriteLine(entry.Key + " = " + entry.Value);
        }

        // close the client
        client.Close();
        Console.WriteLine("Disconnected from server");
    }
}


直接传可能不太好传,但是可以一方序列化成json或者xml,传输过去,再在对方组装成hashmap

示例代码你可以大概看下
java

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;

import com.fasterxml.jackson.databind.ObjectMapper; // 我们使用Jackson库来进行Json序列化

public class SocketServer {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8888);
        System.out.println("Server started. Waiting for connection...");
      
        Socket clientSocket = serverSocket.accept();
        System.out.println("Client connected.");
      
        // 创建一个HashMap对象,将其转换成Json格式的字符串
        HashMap<String, String> data = new HashMap<>();
        data.put("name", "Alice");
        data.put("age", "25");
        data.put("gender", "female");
        String jsonStr = new ObjectMapper().writeValueAsString(data);
      
        OutputStream out = clientSocket.getOutputStream();
        out.write(jsonStr.getBytes());
      
        out.close();
        clientSocket.close();
        serverSocket.close();
    }
}

C#


using System;
using System.IO;
using System.Net.Sockets;
using Newtonsoft.Json; // 我们使用Newtonsoft.Json库来进行Json反序列化

class SocketClient {
    static void Main(string[] args) {
        TcpClient client = new TcpClient();
        client.Connect("localhost", 8888);
      
        Console.WriteLine("Connected to server.");
        StreamReader reader = new StreamReader(client.GetStream());
      
        string response = reader.ReadToEnd();
        Console.WriteLine("Received: " + response);
      
        // 将Json字符串转换成HashMap对象
        var data = JsonConvert.DeserializeObject<System.Collections.Generic.Dictionary<string, string>>(response);
        Console.WriteLine("Name: " + data["name"]);
        Console.WriteLine("Age: " + data["age"]);
        Console.WriteLine("Gender: " + data["gender"]);
      
        reader.Close();
        client.Close();
    }
}

这就是在Java将HashMap对象转换成Json字符串并发送到C#客户端,C#中使用Newtonsoft.Json库将Json字符串反序列化为HashMap对象

可以的 用json传

以下答案由GPT-3.5大模型与博主波罗歌共同编写:
是的,Java 和 C# 通过 Socket 可以互传 HashMap 对象。可以使用 Json 序列化将对象序列化为字符串传输,并在接收端使用相应的反序列化方法将字符串反序列化为对象。

以下是一个简单的实现:

Java 服务端代码:

import java.io.*;
import java.net.*;
import java.util.HashMap;

public class Server {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        ServerSocket serverSocket = new ServerSocket(1234);
        System.out.println("Server started");

        Socket socket = serverSocket.accept();
        System.out.println("Client connected");

        ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
        ObjectInputStream in = new ObjectInputStream(socket.getInputStream());

        // 从客户端接收 HashMap 对象
        HashMap<String, Integer> hashMap = (HashMap<String, Integer>) in.readObject();
        System.out.println("Received HashMap from client: " + hashMap);

        // 修改 HashMap 并发送回客户端
        hashMap.put("C", 3);
        out.writeObject(hashMap);
        System.out.println("Sent modified HashMap back to client: " + hashMap);

        // 关闭连接
        in.close();
        out.close();
        socket.close();
        serverSocket.close();
    }
}

C# 客户端代码:

using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;

public class Client {
    static void Main(string[] args) {
        TcpClient client = new TcpClient("localhost", 1234);
        Console.WriteLine("Client started");

        NetworkStream stream = client.GetStream();
        BinaryFormatter formatter = new BinaryFormatter();

        // 发送HashMap对象到服务端
        Dictionary<string, int> hashMap = new Dictionary<string, int> {
            { "A", 1 },
            { "B", 2 }
        };
        formatter.Serialize(stream, hashMap);
        Console.WriteLine("Sent HashMap to server: {0}", hashMap);

        // 接收服务端发送的修改后的 HashMap 对象
        Dictionary<string, int> modifiedHashMap = (Dictionary<string, int>) formatter.Deserialize(stream);
        Console.WriteLine("Received modified HashMap from server: {0}", modifiedHashMap);

        // 关闭连接
        stream.Close();
        client.Close();
    }
}

这里使用了 BinaryFormatter 进行序列化和反序列化,如果希望使用 Json 序列化可以使用 Json.NET 或 NewtonSoft.Json 等库进行实现。
如果我的回答解决了您的问题,请采纳!

可以互传HashMap对象,以下是Java服务端和C#客户端的Socket和Json序列化代码示例:

img


C#客户端代码:

img