以下是go
、python
的示例代码
- server.py:
import socket
import json
# 服务器配置
HOST = '127.0.0.1' # 服务器的IP地址
PORT = 12345 # 选择一个空闲端口
# 创建一个TCP socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((HOST, PORT))
server_socket.listen()
print(f"服务器正在监听 {HOST}:{PORT}...")
def receive_large_data(client_socket):
data = b''
while True:
chunk = client_socket.recv(1024)
if not chunk:
break
data += chunk
return data
# 等待客户端连接
client_socket, client_address = server_socket.accept()
print(f"已连接到客户端 {client_address}")
# 接收JSON数据
data = receive_large_data(client_socket)
json_data = json.loads(data.decode('utf-8'))
print("接收到的JSON数据:", json_data)
# 关闭连接
client_socket.close()
server_socket.close()
- client.go:
package main
import (
"encoding/json"
"fmt"
"net"
"strings"
)
func main() {
// 服务器配置
serverAddr := "127.0.0.1:12345"
// 连接服务器
conn, err := net.Dial("tcp", serverAddr)
if err != nil {
fmt.Println("无法连接到服务器:", err)
return
}
defer conn.Close()
fmt.Printf("已连接到服务器 %s\n", serverAddr)
// 准备要发送的JSON数据
dataToSend := map[string]interface{}{
"name": "Alice",
"age": 25,
"city": strings.Repeat("Wonderland ", 1000),
}
jsonData, err := json.Marshal(dataToSend)
if err != nil {
fmt.Println("JSON编码失败:", err)
return
}
// 发送JSON数据
_, err = conn.Write(jsonData)
if err != nil {
fmt.Println("发送JSON数据失败:", err)
return
}
fmt.Printf("序列化后的 JSON 数据的字节大小: %d\n", len(jsonData))
}