⭐Unity and Http server send and receive messages (send pictures as an example)

1. Confirm with the server the protocol to be sent (Apipost)

Here you can see that what we need to send is a file file, and the parameter is the picture you want to upload.

2. External configuration files are easy to modify

Get the server IP

3. The script is as follows:

Send data using WWWForm

After receiving the server message, use LitJson to parse it

using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using System.IO;
using UnityEngine.Networking;
using LitJson;

public class BtnTest : MonoBehaviour
{
    public static BtnTest instance;

    //config里拿到的数据
    public string[] Config;
   
    public Button btn;


    public string serverURL; // 服务器URL
    public string videoFieldName; // 视频字段名
    public string videoFilePath; // 视频文件路径

    public MsgClass pngStr;  //图片链接类

    private void Awake()
    {
        instance = this;

        Config = File.ReadAllLines(Application.streamingAssetsPath + "/Config.txt");
        serverURL = Config[0].Split('=')[1];
    }
    // Start is called before the first frame update
    void Start()
    {
        videoFieldName = "file";
        videoFilePath = Application.streamingAssetsPath + "/123.png";

        btn.onClick.AddListener(() =>
        {
            StartCoroutine(SendVideo());
            Debug.Log("向服务器发送图片");
        });
    }
    /// <summary>
    /// 根据本地视频地址向服务器传录好的视频
    /// </summary>
    /// <returns></returns>
    public IEnumerator SendVideo()
    {
        // 创建一个新的表单
        WWWForm form = new WWWForm();

        // 添加视频数据到表单中
        byte[] videoData = System.IO.File.ReadAllBytes(videoFilePath);
        //form.AddField("openid", "123");
        //form.AddField("code", "1002");
        form.AddBinaryData(videoFieldName, videoData);

        // 发送POST请求到服务器
        UnityWebRequest request = UnityWebRequest.Post(serverURL, form);
        yield return request.SendWebRequest();

        if (request.isNetworkError || request.isHttpError)
        {
            Debug.LogError("上传照片成功: " + request.error);
        }
        else
        {
            Debug.Log("照片上传成功!");
            Debug.Log("服务器响应: " + request.downloadHandler.text);
            pngStr= JsonMapper.ToObject<MsgClass>(request.downloadHandler.text);
            Debug.Log("图片网络链接:"+pngStr.fileName);
        }
    }

    /// <summary>
    /// 服务器消息模板
    /// </summary>
    public class MsgClass
    {
        /// <summary>
        /// 暂无互动
        /// </summary>
        public string msg { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string fileName { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public int state { get; set; }
    }
}

4. You can receive messages from the server here~

Guess you like

Origin blog.csdn.net/weixin_53501436/article/details/134531059