本人是新手,但是找了很久都找不到类似的通讯源码,后来终于在一个网站上看到有关于Socket的通讯事例,所以就抄过来希望能够帮助更多像我一样的初学者!嘻嘻

首先创建一个C# 控制台应用程序, 直接服务器端代码丢进去,然后再到Unity 里面建立一个工程,把客户端代码挂到相机上,运行服务端,再运行客户端。 高手勿喷!~!

完全源码已经奉上,大家开始研究吧!! 嘎嘎嘎!

原文链接:http://www.u3dchina.com/forum.php?mod=viewthread&tid=4741&extra=page%3D1%26filter%3Dsortid%26sortid%3D14%26sortid%3D14

服务端代码:Program.cs

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Net.Sockets;
  6. namespace SoketDemo
  7. {
  8. class Program
  9. {
  10. // 设置连接端口
  11. const int portNo = 500;
  12. static void Main(string[] args)
  13. {
  14. // 初始化服务器IP
  15. System.Net.IPAddress localAdd = System.Net.IPAddress.Parse("127.0.0.1");
  16. // 创建TCP侦听器
  17. TcpListener listener = new TcpListener(localAdd, portNo);
  18. listener.Start();
  19. // 显示服务器启动信息
  20. Console.WriteLine("Server is starting...n");
  21. // 循环接受客户端的连接请求
  22. while (true)
  23. {
  24. ChatClient user = new ChatClient(listener.AcceptTcpClient());
  25. // 显示连接客户端的IP与端口
  26. Console.WriteLine(user._clientIP + " is joined...n");
  27. }
  28. }
  29. }
  30. }

复制代码

服务端代码:ChatClient.cs

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Collections;
  6. using System.Net.Sockets;
  7. namespace SoketDemo
  8. {
  9. class ChatClient
  10. {
  11. public static Hashtable ALLClients = new Hashtable(); // 客户列表
  12. private TcpClient _client; // 客户端实体
  13. public string _clientIP; // 客户端IP
  14. private string _clientNick; // 客户端昵称
  15. private byte[] data; // 消息数据
  16. private bool ReceiveNick = true;
  17. public ChatClient(TcpClient client)
  18. {
  19. this._client = client;
  20. this._clientIP = client.Client.RemoteEndPoint.ToString();
  21. // 把当前客户端实例添加到客户列表当中
  22. ALLClients.Add(this._clientIP, this);
  23. data = new byte[this._client.ReceiveBufferSize];
  24. // 从服务端获取消息
  25. client.GetStream().BeginRead(data, 0, System.Convert.ToInt32(this._client.ReceiveBufferSize), ReceiveMessage, null);
  26. }
  27. // 从客戶端获取消息
  28. public void ReceiveMessage(IAsyncResult ar)
  29. {
  30. int bytesRead;
  31. try
  32. {
  33. lock (this._client.GetStream())
  34. {
  35. bytesRead = this._client.GetStream().EndRead(ar);
  36. }
  37. if (bytesRead < 1)
  38. {
  39. ALLClients.Remove(this._clientIP);
  40. Broadcast(this._clientNick + " has left the chat");
  41. return;
  42. }
  43. else
  44. {
  45. string messageReceived = System.Text.Encoding.ASCII.GetString(data, 0, bytesRead);
  46. if (ReceiveNick)
  47. {
  48. this._clientNick = messageReceived;
  49. Broadcast(this._clientNick + " has joined the chat.");
  50. //this.sendMessage("hello");
  51. ReceiveNick = false;
  52. }
  53. else
  54. {
  55. Broadcast(this._clientNick + ">" + messageReceived);
  56. }
  57. }
  58. lock (this._client.GetStream())
  59. {
  60. this._client.GetStream().BeginRead(data, 0, System.Convert.ToInt32(this._client.ReceiveBufferSize), ReceiveMessage, null);
  61. }
  62. }
  63. catch (Exception ex)
  64. {
  65. ALLClients.Remove(this._clientIP);
  66. Broadcast(this._clientNick + " has left the chat.");
  67. }
  68. }
  69. // 向客戶端发送消息
  70. public void sendMessage(string message)
  71. {
  72. try
  73. {
  74. System.Net.Sockets.NetworkStream ns;
  75. lock (this._client.GetStream())
  76. {
  77. ns = this._client.GetStream();
  78. }
  79. // 对信息进行编码
  80. byte[] bytesToSend = System.Text.Encoding.ASCII.GetBytes(message);
  81. ns.Write(bytesToSend, 0, bytesToSend.Length);
  82. ns.Flush();
  83. }
  84. catch (Exception ex)
  85. {
  86. }
  87. }
  88. // 向客户端广播消息
  89. public void Broadcast(string message)
  90. {
  91. Console.WriteLine(message);
  92. foreach (DictionaryEntry c in ALLClients)
  93. {
  94. ((ChatClient)(c.Value)).sendMessage(message + Environment.NewLine);
  95. }
  96. }
  97. }
  98. }

复制代码

客户端代码 :ClientHandler

  1. using UnityEngine;
  2. using System.Collections;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.ComponentModel;
  6. using System.Text;
  7. using System.Net.Sockets;
  8. public class ClientHandler : MonoBehaviour
  9. {
  10. const int portNo = 500;
  11. private TcpClient _client;
  12. byte[] data;
  13. public string nickName = "";
  14. public string message = "";
  15. public string sendMsg = "";
  16. void OnGUI()
  17. {
  18. nickName = GUI.TextField(new Rect(10, 10, 100, 20), nickName);
  19. message = GUI.TextArea(new Rect(10, 40, 300, 200), message);
  20. sendMsg = GUI.TextField(new Rect(10, 250, 210, 20), sendMsg);
  21. if (GUI.Button(new Rect(120, 10, 80, 20), "Connect"))
  22. {
  23. //Debug.Log("hello");
  24. this._client = new TcpClient();
  25. this._client.Connect("127.0.0.1", portNo);
  26. data = new byte[this._client.ReceiveBufferSize];
  27. //SendMessage(txtNick.Text);
  28. SendMessage(nickName);
  29. this._client.GetStream().BeginRead(data, 0, System.Convert.ToInt32(this._client.ReceiveBufferSize), ReceiveMessage, null);
  30. };
  31. if (GUI.Button(new Rect(230, 250, 80, 20), "Send"))
  32. {
  33. SendMessage(sendMsg);
  34. sendMsg = "";
  35. };
  36. }
  37. public void SendMessage(string message)
  38. {
  39. try
  40. {
  41. NetworkStream ns = this._client.GetStream();
  42. byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
  43. ns.Write(data, 0, data.Length);
  44. ns.Flush();
  45. }
  46. catch (Exception ex)
  47. {
  48. //MessageBox.Show(ex.ToString());
  49. }
  50. }
  51. public void ReceiveMessage(IAsyncResult ar)
  52. {
  53. try
  54. {
  55. int bytesRead;
  56. bytesRead = this._client.GetStream().EndRead(ar);
  57. if (bytesRead < 1)
  58. {
  59. return;
  60. }
  61. else
  62. {
  63. Debug.Log(System.Text.Encoding.ASCII.GetString(data, 0, bytesRead));
  64. message += System.Text.Encoding.ASCII.GetString(data, 0, bytesRead);
  65. }
  66. this._client.GetStream().BeginRead(data, 0, System.Convert.ToInt32(this._client.ReceiveBufferSize), ReceiveMessage, null);
  67. }
  68. catch (Exception ex)
  69. {
  70. }
  71. }
  72. }

复制代码

unity中建立 Socket 简单通信相关推荐

  1. C#使用Protocol Buffer(ProtoBuf)进行Unity中的Socket通信

    From: http://www.jb51.net/article/82795.htm 这篇文章主要介绍了C#使用Protocol Buffer(ProtoBuf)进行Unity的Socket通信的实 ...

  2. python实现socket简单通信

    python实现socket简单通信 首先先来简单介绍下socket: (具体更详细介绍的可以在网上找找,都讲得非常详细),这里主要是我自己的一些理解. socket是在应用层与传输层之间的一个抽象层 ...

  3. socket简单通信

    原文:socket简单通信 粗糙简略的初版,后续多加点功能权当练手 /* =============================================================== ...

  4. Keras之ML~P:基于Keras中建立的简单的二分类问题的神经网络模型(根据200个数据样本预测新的5个样本)——概率预测

    Keras之ML~P:基于Keras中建立的简单的二分类问题的神经网络模型(根据200个数据样本预测新的5个样本)--概率预测 目录 输出结果 核心代码 输出结果 核心代码 # -*- coding: ...

  5. Keras之ML~P:基于Keras中建立的简单的二分类问题的神经网络模型(根据200个数据样本预测新的5+1个样本)——类别预测

    Keras之ML~P:基于Keras中建立的简单的二分类问题的神经网络模型(根据200个数据样本预测新的5+1个样本)--类别预测 目录 输出结果 核心代码 输出结果 核心代码 # -*- codin ...

  6. 【Unity3D 灵巧小知识点】 ☀️ | Unity中几个简单又常见的报错异常

    Unity 小科普 老规矩,先介绍一下 Unity 的科普小知识: Unity是 实时3D互动内容创作和运营平台 . 包括游戏开发.美术.建筑.汽车设计.影视在内的所有创作者,借助 Unity 将创意 ...

  7. unity中Time.delaTime简单解释

    unity中Time.delaTime简单解释 在项目中控制物体移动,物体的运动速度忽快忽慢. 这是由于物体的位置变化是按照帧率刷新的. /// <summary>/// 每帧刷新/// ...

  8. c语言实现 windows socket_C语言实现Socket简单通信

    点击上方"学士科技",选择"设为星标" 资讯.技术干货第一时间送达! C语言基础合集,点我点我~~~ C语言进阶合集,点我点我~~~ C语言高级: 01.C语言 ...

  9. c语言 socket 报文解析,C语言实现Socket简单通信

    环境是linux,不过应该没什么影响,因为只用到了socket的基本用法,没有涉及pthread等. 分为服务器端和客户端,服务器端监听端口发来的请求,收到后向客户端发送一个Hello World,客 ...

最新文章

  1. 百度编辑器(1.4.3—net版)上传图片路径及其他配置
  2. 最大值(3.3)(java)
  3. dubbo部分常见的面试题目
  4. 从零开始学习Sencha Touch MVC应用之七
  5. 在java中下列描述错误的是_在 JAVA 中 , 关于类的方法 , 下列描述错误的是 ()._学小易找答案...
  6. Linux 修改 IP地址 和 网关
  7. 使用Ant Design 和Vue,React中后台开发套餐
  8. OpenGL 颜色Colors
  9. Jenkins 基本概念与简介
  10. 项目启动:java程序包不存在_ideaError:(3, 24) java: 程序包不存在的问题
  11. Android8.0学习(1)---Android 架构
  12. 表贴电阻尺寸与什么有关_0欧电阻存在的意义?看了就懂了
  13. c语言 连通域算法 递归,VC++ 6.0编写计算机图形学中的种子填充算法,想用递归的八向连通域,求助!...
  14. python斐波那契递归_Python递归斐波那契示例
  15. atitit.spring3 mvc url配置最佳实践
  16. 网络安全行业全景图(2019年1月)
  17. C语言与线性代数,编程与线性代数
  18. 图解机器学习算法(3) | KNN算法及其应用(机器学习通关指南·完结)
  19. 用python爬虫爬取图虫网站图片
  20. GNU 软件文档下载

热门文章

  1. 干货 | 携程桌面应用的前端内存优化与监控
  2. java项目2个数据源_springboot项目配置两个数据源的方法
  3. 画江湖盟主侠岚篇怎么在电脑上玩 画江湖盟主电脑版玩法教程
  4. excel明细生成多个word文档,比邮件合并好用100倍。
  5. 使用realloc注意
  6. 修改sepolicy后编译出现‘Error while expanding policy’【转】
  7. PCB工程师这几点习惯
  8. node之process
  9. 无线黑名单实现(将终端踢下线同时禁止终端再次连接)
  10. 4p营销组合策略案例_营销4P到底是什么?理解营销4P订定你的营销策略架构