Unity - A计划(永久有效期) 扫二维码继续学习 二维码时效为半小时

(196评价)
价格: 4059.00元
C#高级教程 605-unity聊天室
zecymo发起了话题2019-02-08
2
回复
266
浏览

停止unity端时抛出异常 这个是什么原因造成的

 

namespace tttt
{
    //新建一个类,用于处理收到的连接
    class Clients
    {
        private Socket clientSocket;
        private Thread t;
        private byte[] data=new byte[1024];
        public Clients(Socket s)
        {
            Console.WriteLine("构造。。。");
            clientSocket = s;
            t =new Thread(ReceiveMsg);
            t.Start();
        }
        


        void ReceiveMsg()
        {
            while (true)
            {
                Console.WriteLine("aaaaaa");
                if (clientSocket.Poll(10,SelectMode.SelectRead))
                {
                    Console.WriteLine("bbbbb");
                    break;
                }

                int length = clientSocket.Receive(data);
                string msg = Encoding.UTF8.GetString(data, 0, length);
                Console.WriteLine("接受的数据:"+msg);
            }
        }

    }
}

//unity端
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using UnityEngine;
using UnityEngine.UI;

public class ClientScript : MonoBehaviour
{

    private Socket clientSocket;
    private string message;

    public string ipAddress = "192.168.31.106";
    public int port = 7788;

    public Text ChaText;
    public InputField MsgInputField;


    void Start () {
		ConnectToServer();
	}
	
	// Update is called once per frame
	void Update () {
        if (message!=null && message!="")
        {
            ChaText.text += "\n" + message;
            message = "";
        }	
	}

    void ConnectToServer()
    {
        //连接到服务器
        clientSocket = new socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
        EndPoint point = new IPEndPoint(IPAddress.Parse(ipAddress), port);
        clientSocket.Connect(point);

    }

     public void SendMsg()
    {
        byte[] msgBytes = Encoding.UTF8.GetBytes(MsgInputField.text);
        print(MsgInputField.text);
        //MsgInputField.text = "";
        clientSocket.Send(msgBytes);
    }

     void OnDestroy()
     {
         clientSocket.Shutdown(SocketShutdown.Both);
         clientSocket.Close();
     }

}

 

 

所有回复
  • zecymo 2019-02-08

    图看不清 异常是

    “System.Net.Sockets.SocketException”类型的未经处理的异常在 System.dll 中发生 
    远程主机强迫关闭了一个现有的连接。”

    还有-5条回复,点击查看
    你还没有登录,请先登录注册
  • 老师_Trigger 2019-02-09

    同学你好,参考一下这篇文章:

    http://www.codes51.com/itwd/1675560.html

    还有-5条回复,点击查看
    你还没有登录,请先登录注册
发表回复
你还没有登录,请先 登录或 注册!