unity3d之sokect通信

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Linq;
using System.Text;

using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using UnityEngine.UI;

public class ss : MonoBehaviour {
    public TcpClient client;
    public BinaryReader breader;
    public BinaryWriter bwriter;
    public NetworkStream netstream;
    public float m_speed = 5f;
   
    // Use this for initialization
    void Start () {

        client = new TcpClient("127.0.0.1", 8139);
        netstream = client.GetStream();
        breader = new BinaryReader(netstream);
        bwriter = new BinaryWriter(netstream);


        Thread threadReceive = new Thread(new ThreadStart(ReceiveData));
        threadReceive.IsBackground = true;
        threadReceive.Start();


    }
    private void ReceiveData()
    {
        //Text text;
        string receiveSting = null;
       //text = GameObject.Find("Canvas/Text").GetComponent<Text>();


        receiveSting = breader.ReadString();
     //text.text += receiveSting;

    }
    // Update is called once per frame
    void Update () {
        if (Input.GetKey(KeyCode.W) | Input.GetKey(KeyCode.UpArrow)) //前
        {
            this.transform.Translate(Vector3.forward * m_speed * Time.deltaTime);
            bwriter.Write("w下");
            bwriter.Flush();
        }
        if (Input.GetKey(KeyCode.S) | Input.GetKey(KeyCode.DownArrow)) //后
        {
            this.transform.Translate(Vector3.forward * -m_speed * Time.deltaTime);
            bwriter.Write("s上");
            bwriter.Flush();
        }
        if (Input.GetKey(KeyCode.A) | Input.GetKey(KeyCode.LeftArrow)) //左
        {
            this.transform.Translate(Vector3.right * -m_speed * Time.deltaTime);
            bwriter.Write("a左");
            bwriter.Flush();
        }
        if (Input.GetKey(KeyCode.D) | Input.GetKey(KeyCode.RightArrow)) //右
        {
            this.transform.Translate(Vector3.right * m_speed * Time.deltaTime);
            bwriter.Write("d右");
            bwriter.Flush();
        }
    }
}

1.unity里不能搭建服务器端

可以搭建客户端

除非unity3d封装的网络游戏的类

2.最好不要用C#封装的tcpclient等封装类,使用socket,否则与其他语言服务器对接会有问题

3.接受服务器端的信息无法关闭线程保护来避免

“线程间操作无效: 从不是创建控件“ ”的线程访问它”

协程没用过

(1)估计必须使用委托来跨线程调用; 

才能调用其它unity3d的其他组件

(2)设置全局变量,子线程改变全局变量

(3)用unity3d封装的网络游戏的类


4.unity3d不支持后台线程

参考http://www.manew.com/thread-98363-1-1.html

https://www.zhihu.com/question/52057063?sort=created


原文地址:https://www.cnblogs.com/fengmao31/p/13880208.html