博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Unity3d 脚本与C#Socket服务器传输数据
阅读量:4619 次
发布时间:2019-06-09

本文共 5824 字,大约阅读时间需要 19 分钟。

Test.cs脚本

---------------------------------------------------------------------------------------------------------------------------------------------------

using System.Collections;

using System.Collections.Generic;
using UnityEngine;
using AssemblyCSharp;
using System.Text;
using System;
using System.Threading;

public class Test : MonoBehaviour {

  private JFSocket mJFSocket;
  // Use this for initialization
  void Start () {

    mJFSocket = JFSocket.GetInstance();

  }
  // Update is called once per frame
  void Update () {
    if(mJFSocket!=null){
      Debug.Log (mJFSocket.receive_msg);
    }
  }
}

---------------------------------------------------------------------------------------------------------------------------------------------------

SocketClientTest.cs

---------------------------------------------------------------------------------------------------------------------------------------------------

using UnityEngine;

using System.Collections;
using System;
using System.Threading;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace AssemblyCSharp
{
  public class SocketClientTest
  {
    //Socket客户端对象
    private Socket clientSocket;
    //单例模式
    private static SocketClientTest instance;
    public string receive_msg = "";
    public static SocketClientTest GetInstance()
    {
      if (instance == null)
      {
        instance = new SocketClientTest();
      }
      return instance;
    }
    //单例的构造函数
    SocketClientTest()
    {
      //创建Socket对象, 这里我的连接类型是TCP
      clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
      //服务器IP地址
      IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
      //服务器端口
      IPEndPoint ipEndpoint = new IPEndPoint(ipAddress, 5209);
      //这是一个异步的建立连接,当连接建立成功时调用connectCallback方法
      IAsyncResult result = clientSocket.BeginConnect(ipEndpoint, new AsyncCallback(connectCallback), clientSocket);
      //这里做一个超时的监测,当连接超过5秒还没成功表示超时
      bool success = result.AsyncWaitHandle.WaitOne(5000, true);
      if (!success)
      {
        //超时
        Closed();
        Debug.Log("connect Time Out");
      }
      else
      {
        //Debug.Log ("与socket建立连接成功,开启线程接受服务端数据");
        //与socket建立连接成功,开启线程接受服务端数据。
        Thread thread = new Thread(new ThreadStart(ReceiveSorketMsg));
        thread.IsBackground = true;
        thread.Start();
      }
    }
    private void connectCallback(IAsyncResult asyncConnect)
    {
      Debug.Log("connectSuccess");
    }

    private void ReceiveSorketMsg()

    {
      Console.WriteLine ("wait---");
      //在这个线程中接受服务器返回的数据
      while (true)
      {
        if (!clientSocket.Connected)
        {
          //与服务器断开连接跳出循环
          Debug.Log("Failed to clientSocket server.");
          clientSocket.Close();
          break;
        }
        try
        {
          //接受数据保存至bytes当中
          byte[] bytes = new byte[4096];
          //Receive方法中会一直等待服务端回发消息
          //如果没有回发会一直在这里等着。
          int i = clientSocket.Receive(bytes);
          if (i <= 0)
          {
            clientSocket.Close();
            break;
          }
          Debug.Log(Encoding.ASCII.GetString(bytes, 0, i));
          if (bytes.Length > 8)
          {
            //Console.WriteLine("接收服务器消息:{0}", Encoding.ASCII.GetString(bytes, 0, i));
            receive_msg = Encoding.ASCII.GetString(bytes, 0, i);
          }
          else
          {
            Debug.Log("length is not > 8");
          }
        }
        catch (Exception e)
        {
          Debug.Log("Failed to clientSocket error." + e);
          clientSocket.Close();
          break;
        }
      }
    }

    //关闭Socket

    public void Closed()
    {
      if (clientSocket != null && clientSocket.Connected)
      {
        clientSocket.Shutdown(SocketShutdown.Both);
        clientSocket.Close();
      }
      clientSocket = null;
    }
  }
}

 

---------------------------------------------------------------------------------------------------------------------------------------------------

 

Socket服务端代码:

 

using System;

using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace SocketServerTest01

{
  class Program
  {
    private static byte[] result = new byte[1024];
    private static int myProt = 5209; //端口
    static Socket serverSocket;
    static void Main(string[] args)
    {
      //服务器IP地址
      IPAddress ip = IPAddress.Parse("127.0.0.1");
      serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
      serverSocket.Bind(new IPEndPoint(ip, myProt)); //绑定IP地址:端口
      serverSocket.Listen(10); //设定最多10个排队连接请求
      Console.WriteLine("启动监听{0}成功", serverSocket.LocalEndPoint.ToString());
      //通过Clientsoket发送数据
      Socket clientSocket = serverSocket.Accept();
      while (true) {
        Thread.Sleep(1000);
        SendMsg(clientSocket);
      }
    }

    /// <summary>

    /// 以每秒一次的频率发送数据给客户端
    /// </summary>
    /// <param name="clientSocket"></param>
    public static void SendMsg(Socket clientSocket)
    {
      try
      {
        clientSocket.Send(Encoding.ASCII.GetBytes(GetRandomData()));
      }
      catch {
        Console.WriteLine("服务器异常");
        return;
      }
    }

    /// <summary>

    /// 产生随机字符串
    /// </summary>
    /// <returns></returns>
    private static string GetRandomData()
    {
      Random ran = new Random();
      int x = ran.Next(50,200);
      int y = ran.Next(20,100);
      int z = 1000;
      int ID = ran.Next(1,30);
      string str = "ID:"+ID+"-x:"+x+"-y:"+y+"-z:"+z;
      return str;
    }
  }
}

 

转载于:https://www.cnblogs.com/herd/p/7053756.html

你可能感兴趣的文章
MySql【Error笔记】
查看>>
vue入门
查看>>
JS线程Web worker
查看>>
Flex的动画效果与变换!(三)(完)
查看>>
mysql常见错误码
查看>>
Openresty 与 Tengine
查看>>
使用XV-11激光雷达做hector_slam
查看>>
布局技巧4:使用ViewStub
查看>>
ddt Ui 案例2
查看>>
你还在为使用P/Invoke时,写不出win32 api对应的C#声明而犯愁吗?
查看>>
msbuild property metadata会overwrite msbuild task中的properties
查看>>
python系列前期笔记
查看>>
Android -- sqlite数据库随apk发布
查看>>
Android -- Fragment
查看>>
前端性能优化和规范
查看>>
python 之进程篇
查看>>
框架编程之路一
查看>>
Verilog学习----运算符、结构说明语句
查看>>
需求分析报告
查看>>
第四次作业
查看>>