Unity C# Network Learning (9) - WWWFrom
- If you want to use WWW to upload data, you need to use it with the WWWFrom class
- The main request type it uses is Post
- Using WWWFrom to upload data generally needs to cooperate with the back-end program to formulate upload rules
1. WWWFrom class
1. Common methods of WWWFrom class
WWWForm wwwForm = new WWWForm();
wwwForm.AddBinaryData("xxx", new byte[10]);
wwwForm.AddField("name", "zzs", Encoding.UTF8);
2. WWW combines WWWFrom object to upload data asynchronously
private IEnumerator UpLoadData()
{
WWWForm data = new WWWForm();
data.AddField("Name", "zzs", Encoding.UTF8);
data.AddField("Age", 18);
data.AddBinaryData("file",File.ReadAllBytes(Application.streamingAssetsPath +"/test.jpg"),"myTest.jpg","application/octet-stream");
WWW www = new WWW("http://192.168.1.103:8080/Http_Server/", data);
yield return www;
if (www.error == null && www.isDone)
{
Debug.Log("上传成功!");
}
else
{
Debug.Log("上传失败!" + www.error);
}
}
Two. WWWFrom send data
public void SendMsg<T>(MsgBase msg,Action<T> action) where T: MsgBase
{
StartCoroutine(SendMsgAsync(msg,action));
}
private IEnumerator SendMsgAsync<T>(MsgBase msg,Action<T> action)where T: MsgBase
{
WWWForm wwwForm = new WWWForm();
wwwForm.AddBinaryData("Msg",msg.ToArray());
WWW www = new WWW(RootUrl,wwwForm);
yield return www;
if (www.error == null)
{
int index = 0;
int msgId = BitConverter.ToInt32(www.bytes, 0);
index += 4;
int length = BitConverter.ToInt32(www.bytes, index);
index += 4;
MsgBase msgBase = null;
switch (msgId)
{
case 1001:
msgBase = new PlayerMsg();
msgBase.Reading(www.bytes, index);
break;
}
if (msgBase != null)
{
action?.Invoke(msgBase as T);
}
}
else
{
Debug.Log("发消息出现问题:"+www.error);
}
}