unity中建立 Socket 简单通信
本人是新手,但是找了很久都找不到类似的通讯源码,后来终于在一个网站上看到有关于Socket的通讯事例,所以就抄过来希望能够帮助更多像我一样的初学者!嘻嘻
首先创建一个C# 控制台应用程序, 直接服务器端代码丢进去,然后再到Unity 里面建立一个工程,把客户端代码挂到相机上,运行服务端,再运行客户端。 高手勿喷!~!
完全源码已经奉上,大家开始研究吧!! 嘎嘎嘎!
原文链接:http://www.u3dchina.com/forum.php?mod=viewthread&tid=4741&extra=page%3D1%26filter%3Dsortid%26sortid%3D14%26sortid%3D14
服务端代码:Program.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Net.Sockets;
- namespace SoketDemo
- {
- class Program
- {
- // 设置连接端口
- const int portNo = 500;
- static void Main(string[] args)
- {
- // 初始化服务器IP
- System.Net.IPAddress localAdd = System.Net.IPAddress.Parse("127.0.0.1");
- // 创建TCP侦听器
- TcpListener listener = new TcpListener(localAdd, portNo);
- listener.Start();
- // 显示服务器启动信息
- Console.WriteLine("Server is starting...n");
- // 循环接受客户端的连接请求
- while (true)
- {
- ChatClient user = new ChatClient(listener.AcceptTcpClient());
- // 显示连接客户端的IP与端口
- Console.WriteLine(user._clientIP + " is joined...n");
- }
- }
- }
- }
复制代码
服务端代码:ChatClient.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Collections;
- using System.Net.Sockets;
- namespace SoketDemo
- {
- class ChatClient
- {
- public static Hashtable ALLClients = new Hashtable(); // 客户列表
- private TcpClient _client; // 客户端实体
- public string _clientIP; // 客户端IP
- private string _clientNick; // 客户端昵称
- private byte[] data; // 消息数据
- private bool ReceiveNick = true;
- public ChatClient(TcpClient client)
- {
- this._client = client;
- this._clientIP = client.Client.RemoteEndPoint.ToString();
- // 把当前客户端实例添加到客户列表当中
- ALLClients.Add(this._clientIP, this);
- data = new byte[this._client.ReceiveBufferSize];
- // 从服务端获取消息
- client.GetStream().BeginRead(data, 0, System.Convert.ToInt32(this._client.ReceiveBufferSize), ReceiveMessage, null);
- }
- // 从客戶端获取消息
- public void ReceiveMessage(IAsyncResult ar)
- {
- int bytesRead;
- try
- {
- lock (this._client.GetStream())
- {
- bytesRead = this._client.GetStream().EndRead(ar);
- }
- if (bytesRead < 1)
- {
- ALLClients.Remove(this._clientIP);
- Broadcast(this._clientNick + " has left the chat");
- return;
- }
- else
- {
- string messageReceived = System.Text.Encoding.ASCII.GetString(data, 0, bytesRead);
- if (ReceiveNick)
- {
- this._clientNick = messageReceived;
- Broadcast(this._clientNick + " has joined the chat.");
- //this.sendMessage("hello");
- ReceiveNick = false;
- }
- else
- {
- Broadcast(this._clientNick + ">" + messageReceived);
- }
- }
- lock (this._client.GetStream())
- {
- this._client.GetStream().BeginRead(data, 0, System.Convert.ToInt32(this._client.ReceiveBufferSize), ReceiveMessage, null);
- }
- }
- catch (Exception ex)
- {
- ALLClients.Remove(this._clientIP);
- Broadcast(this._clientNick + " has left the chat.");
- }
- }
- // 向客戶端发送消息
- public void sendMessage(string message)
- {
- try
- {
- System.Net.Sockets.NetworkStream ns;
- lock (this._client.GetStream())
- {
- ns = this._client.GetStream();
- }
- // 对信息进行编码
- byte[] bytesToSend = System.Text.Encoding.ASCII.GetBytes(message);
- ns.Write(bytesToSend, 0, bytesToSend.Length);
- ns.Flush();
- }
- catch (Exception ex)
- {
- }
- }
- // 向客户端广播消息
- public void Broadcast(string message)
- {
- Console.WriteLine(message);
- foreach (DictionaryEntry c in ALLClients)
- {
- ((ChatClient)(c.Value)).sendMessage(message + Environment.NewLine);
- }
- }
- }
- }
复制代码
客户端代码 :ClientHandler
- using UnityEngine;
- using System.Collections;
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Text;
- using System.Net.Sockets;
- public class ClientHandler : MonoBehaviour
- {
- const int portNo = 500;
- private TcpClient _client;
- byte[] data;
- public string nickName = "";
- public string message = "";
- public string sendMsg = "";
- void OnGUI()
- {
- nickName = GUI.TextField(new Rect(10, 10, 100, 20), nickName);
- message = GUI.TextArea(new Rect(10, 40, 300, 200), message);
- sendMsg = GUI.TextField(new Rect(10, 250, 210, 20), sendMsg);
- if (GUI.Button(new Rect(120, 10, 80, 20), "Connect"))
- {
- //Debug.Log("hello");
- this._client = new TcpClient();
- this._client.Connect("127.0.0.1", portNo);
- data = new byte[this._client.ReceiveBufferSize];
- //SendMessage(txtNick.Text);
- SendMessage(nickName);
- this._client.GetStream().BeginRead(data, 0, System.Convert.ToInt32(this._client.ReceiveBufferSize), ReceiveMessage, null);
- };
- if (GUI.Button(new Rect(230, 250, 80, 20), "Send"))
- {
- SendMessage(sendMsg);
- sendMsg = "";
- };
- }
- public void SendMessage(string message)
- {
- try
- {
- NetworkStream ns = this._client.GetStream();
- byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
- ns.Write(data, 0, data.Length);
- ns.Flush();
- }
- catch (Exception ex)
- {
- //MessageBox.Show(ex.ToString());
- }
- }
- public void ReceiveMessage(IAsyncResult ar)
- {
- try
- {
- int bytesRead;
- bytesRead = this._client.GetStream().EndRead(ar);
- if (bytesRead < 1)
- {
- return;
- }
- else
- {
- Debug.Log(System.Text.Encoding.ASCII.GetString(data, 0, bytesRead));
- message += System.Text.Encoding.ASCII.GetString(data, 0, bytesRead);
- }
- this._client.GetStream().BeginRead(data, 0, System.Convert.ToInt32(this._client.ReceiveBufferSize), ReceiveMessage, null);
- }
- catch (Exception ex)
- {
- }
- }
- }
复制代码
unity中建立 Socket 简单通信相关推荐
- C#使用Protocol Buffer(ProtoBuf)进行Unity中的Socket通信
From: http://www.jb51.net/article/82795.htm 这篇文章主要介绍了C#使用Protocol Buffer(ProtoBuf)进行Unity的Socket通信的实 ...
- python实现socket简单通信
python实现socket简单通信 首先先来简单介绍下socket: (具体更详细介绍的可以在网上找找,都讲得非常详细),这里主要是我自己的一些理解. socket是在应用层与传输层之间的一个抽象层 ...
- socket简单通信
原文:socket简单通信 粗糙简略的初版,后续多加点功能权当练手 /* =============================================================== ...
- Keras之ML~P:基于Keras中建立的简单的二分类问题的神经网络模型(根据200个数据样本预测新的5个样本)——概率预测
Keras之ML~P:基于Keras中建立的简单的二分类问题的神经网络模型(根据200个数据样本预测新的5个样本)--概率预测 目录 输出结果 核心代码 输出结果 核心代码 # -*- coding: ...
- Keras之ML~P:基于Keras中建立的简单的二分类问题的神经网络模型(根据200个数据样本预测新的5+1个样本)——类别预测
Keras之ML~P:基于Keras中建立的简单的二分类问题的神经网络模型(根据200个数据样本预测新的5+1个样本)--类别预测 目录 输出结果 核心代码 输出结果 核心代码 # -*- codin ...
- 【Unity3D 灵巧小知识点】 ☀️ | Unity中几个简单又常见的报错异常
Unity 小科普 老规矩,先介绍一下 Unity 的科普小知识: Unity是 实时3D互动内容创作和运营平台 . 包括游戏开发.美术.建筑.汽车设计.影视在内的所有创作者,借助 Unity 将创意 ...
- unity中Time.delaTime简单解释
unity中Time.delaTime简单解释 在项目中控制物体移动,物体的运动速度忽快忽慢. 这是由于物体的位置变化是按照帧率刷新的. /// <summary>/// 每帧刷新/// ...
- c语言实现 windows socket_C语言实现Socket简单通信
点击上方"学士科技",选择"设为星标" 资讯.技术干货第一时间送达! C语言基础合集,点我点我~~~ C语言进阶合集,点我点我~~~ C语言高级: 01.C语言 ...
- c语言 socket 报文解析,C语言实现Socket简单通信
环境是linux,不过应该没什么影响,因为只用到了socket的基本用法,没有涉及pthread等. 分为服务器端和客户端,服务器端监听端口发来的请求,收到后向客户端发送一个Hello World,客 ...
最新文章
- 华三h3c交换机最详细的配置实例手册_华为/思科/华三基本命令对比
- 树莓派迅雷远程下载 | 树莓派小无相系列
- access2013数据库实验笔记_医学科研实验基础知识笔记(十):甲基化
- php object添加到数组,PHP Object转换为数组array
- 云服务器文件传输问题
- 从0开始学习自动化测试框架cypress(五)总结
- Java-Volatile的实现(待删除)
- Qweb Pdf 中添加 图片
- 在python中怎么排序_怎么在python的字典中进行排序
- 11个好用的黑科技资源搜索网站
- java 生成水印_Java实现图片生成水印
- linux下检查磁盘是否有坏道,badblocks 检查硬盘是否有坏道
- IIS 发布网站无法显示CSS、背景及图片文件---另一个思路--终极方案
- 你对自己的定位是什么,就能成为什么样的人(转)
- word没自动保存?===如何通过asd文件恢复
- 永洪科技怎么样_「永洪科技」
- JEECG常见问题大全
- 大淘客cms php版本,大淘客cms频繁出现 500错误页面临时解决方法
- C语言有大约40个运算符,最常用的有这些
- LL(1)文法中FIRST集和FOLLOW集的计算方法