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;
    }
  }
}

Unity3d 脚本与C#Socket服务器传输数据的更多相关文章

  1. [转]unity3d 脚本参考-技术文档

    unity3d 脚本参考-技术文档 核心提示:一.脚本概览这是一个关于Unity内部脚本如何工作的简单概览.Unity内部的脚本,是通过附加自定义脚本对象到游戏物体组成的.在脚本对象内部不同志的函数被 ...

  2. workerman是一个高性能的PHP socket服务器框架

    workerman-chatorkerman是一款纯PHP开发的开源高性能的PHP socket服务器框架.被广泛的用于手机app.手游服务端.网络游戏服务器.聊天室服务器.硬件通讯服务器.智能家居. ...

  3. Unity3D脚本中文系列教程(十五)

    http://dong2008hong.blog.163.com/blog/static/4696882720140322449780/ Unity3D脚本中文系列教程(十四) ◆ LightRend ...

  4. Unity3D脚本中文系列教程(十四)

    http://dong2008hong.blog.163.com/blog/static/469688272014032134394/ WWWFrom 类Unity3D脚本中文系列教程(十三)辅助类. ...

  5. Unity3D脚本中文系列教程(十)

    http://dong2008hong.blog.163.com/blog/static/4696882720140312627682/?suggestedreading&wumii Unit ...

  6. Unity3D脚本中文系列教程(四)

    http://dong2008hong.blog.163.com/blog/static/4696882720140302451146/ Unity3D脚本中文系列教程(三) 送到动画事件. ◆ va ...

  7. Unity3D教程宝典之Web服务器篇:(第二讲)从服务器下载图片

    转载自风宇冲Unity3D教程学院                                    从Web服务器下载图片 上一讲风宇冲介绍了wamp服务器及安装.这回介绍如何从服务器下载内容至 ...

  8. 通过监控线程状态来保证socket服务器的稳定运行

    云平台中使用的socket服务器是我们自己定义一套通信协议,并通过C#实现的一个socket服务. 该服务目前是和web服务一起运行在IIS容器中,通过启动一个永不退出的新线程来监听端口. 在开发的初 ...

  9. Java NIO 非阻塞Socket服务器构建

    推荐阅读IBM developerWorks中NIO的入门教程,尤其是对块I/O和流I/O不太清楚的开发者. 说到socket服务器,第一反应是java.net.Socket这个类.事实上在并发和响应 ...

随机推荐

  1. Ubuntu下常用的快捷键

    熟练地快捷键操作可以大大的节省我们的时间,下面贴上一些快捷键的操作: 桌面常用快捷键 Alt + F1:聚焦到桌面左侧任务导航栏,可按上下键进行导航 Alt + F2:运行命令 Alt + F4:关闭 ...

  2. vue router按需加载

    import Vue from 'vue' import Router from 'vue-router' Vue.use(Router); //按需加载,当渲染其他页面时才加载其组件,并缓存,减少首 ...

  3. linux 处理端口

    1.查看8080端口是否被占用: netstat -anp | grep 8080 2.查看占用8080端口的进程:fuser -v -n tcp 8080 3.杀死占用8080端口的进程: kill ...

  4. hdu--1878--欧拉回路(并查集判断连通,欧拉回路模板题)

     题目链接 /* 模板题-------判断欧拉回路 欧拉路径,无向图 1判断是否为连通图, 2判断奇点的个数为0 */ #include <iostream> #include <c ...

  5. uva120 Stacks of Flapjacks (构造法)

    这个题没什么算法,就是想出怎么把答案构造出来就行. 思路:越大的越放在底端,那么每次就找出还没搞定的最大的,把它移到当前还没定好的那些位置的最底端,定好的就不用管了. 这道题要处理好输入,每次输入的一 ...

  6. python 类的定义和继承

    python 2 中类 一.类定义: ? 1 2 class <类名>:   <语句> 类实例化后,可以使用其属性,实际上,创建一个类之后,可以通过类名访问其属性如果直接使用类 ...

  7. [转]【技术心得】Last-Modified,Etag,Expire区别

    Last-Modified 是什么 Last-Modified 是 HttpHeader 中的资源的最后修改时间,如果带有 Last-Modified ,下一次发送 Http 请求时,将会发生带 If ...

  8. 媒体查询ipad,pc端

    媒体查询 /* 判断ipad */ @media only screen and (min-device-width : 768px) and (max-device-width : 1024px){ ...

  9. centos7 安装 mysql-python时 报错 EnvironmentError: mysql_config not found

    pip install mysql-python 然后报错 EnvironmentError: mysql_config not found 网上搜解决方法,需要安装   mysql-devel 然后 ...

  10. Day1作业---登录接口及多级菜单

    #!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Ma Qing data = { "山东" :{ "济南&qu ...