-
websocket python unity_Unity中Websocket的简单使用
2020-12-11 11:26:43Unity中Websocket的简单使用发布时间:2020-02-23 01:06:05来源:51CTO阅读:19393首先我们需要一个websocket服务器,之前的博文中有做Tomcat架设简单Websocket服务器用的时候打开就行了,先不管它Unity中新建场景建...Unity中Websocket的简单使用
发布时间:2020-02-23 01:06:05
来源:51CTO
阅读:19393
首先我们需要一个websocket服务器,之前的博文中有做
Tomcat架设简单Websocket服务器
用的时候打开就行了,先不管它
Unity中新建场景
建UI(UGUI)
有一个连接按钮Button
一个信息输入框InputField
一个发送按钮Button
一个断开按钮Button
一个消息显示框Text
场景中建一个GameObject,在上面加个脚本,就叫WSMgr好了
用到了BestHTTP这个插件using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using BestHTTP;
using BestHTTP.WebSocket;
using System;
using BestHTTP.Examples;
using UnityEngine.UI;
using System.Text;
public class WSMgr : MonoBehaviour {
//public string url = "ws://localhost:8080/web1/websocket";
public string url = "ws://localhost:8080/web1/ws";
public InputField msg;
public Text console;
private WebSocket webSocket;
private void Start()
{
init();
}
private void init()
{
webSocket = new WebSocket(new Uri(url));
webSocket.OnOpen += OnOpen;
webSocket.OnMessage += OnMessageReceived;
webSocket.OnError += OnError;
webSocket.OnClosed += OnClosed;
}
private void antiInit()
{
webSocket.OnOpen = null;
webSocket.OnMessage = null;
webSocket.OnError = null;
webSocket.OnClosed = null;
webSocket = null;
}
private void setConsoleMsg(string msg)
{
console.text = "Message: " + msg;
}
public void Connect()
{
webSocket.Open();
}
private byte[] getBytes(string message)
{
byte[] buffer = Encoding.Default.GetBytes(message);
return buffer;
}
public void Send()
{
webSocket.Send(msg.text);
}
public void Send(string str)
{
webSocket.Send(str);
}
public void Close()
{
webSocket.Close();
}
#region WebSocket Event Handlers
///
/// Called when the web socket is open, and we are ready to send and receive data
///
void OnOpen(WebSocket ws)
{
Debug.Log("connected");
setConsoleMsg("Connected");
}
///
/// Called when we received a text message from the server
///
void OnMessageReceived(WebSocket ws, string message)
{
Debug.Log(message);
setConsoleMsg(message);
}
///
/// Called when the web socket closed
///
void OnClosed(WebSocket ws, UInt16 code, string message)
{
Debug.Log(message);
setConsoleMsg(message);
antiInit();
init();
}
private void OnDestroy()
{
if(webSocket!=null && webSocket.IsOpen)
{
webSocket.Close();
antiInit();
}
}
///
/// Called when an error occured on client side
///
void OnError(WebSocket ws, Exception ex)
{
string errorMsg = string.Empty;
#if !UNITY_WEBGL || UNITY_EDITOR
if (ws.InternalRequest.Response != null)
errorMsg = string.Format("Status Code from Server: {0} and Message: {1}", ws.InternalRequest.Response.StatusCode, ws.InternalRequest.Response.Message);
#endif
Debug.Log(errorMsg);
setConsoleMsg(errorMsg);
antiInit();
init();
}
#endregion
}
Connect Send Close 三个方法对应的就是三个按钮的功能
OnOpen OnMessage OnError OnClose这四个一看就是Websocket的四个事件对应的方法
首先在Start方法中init()
点击Connect,连接
在输入框中输入,点击Send就发送
点击Close断开连接
底部的Text中会显示消息
同样,Tomcat服务端也有显示
发布WebGL测试可用
-
websocket python unity_Unity3d 下websocket的使用
2020-12-11 11:26:45今天介绍一下如何在Unity3D下使用WebSocket。首先介绍一下什么是websocket,以及与socket,和http的区别与联系,然后介绍一下websocket的一些开源的项目。WebSocket是什么WebSocket协议是为了实现网络客户端和服务器...今天介绍一下如何在Unity3D下使用WebSocket。
首先介绍一下什么是websocket,以及与socket,和http的区别与联系,然后介绍一下websocket的一些开源的项目。
WebSocket是什么
WebSocket协议是为了实现网络客户端和服务器端全双工通信而引入的一种基于消息帧和TCP的通信机制,这个协议本身的目标是为了在http服务器上引入双向通信的机制,从而克服http单向通信的缺陷(http设计的初衷就不是为了双向通信),其可以在复用http的端口,支持http的代理,认证等,虽然如此,websocket可以独立于http存在。
详细的内容可以参考RFC6455(https://datatracker.ietf.org/doc/rfc6455/)里面有详细的介绍。
那么WebSocket与http,socket有什么区别和联系呢。
WebSocket和http
其实从历史上来讲,websocket是为了克服http无法双向通信而引入的,在通常的使用中,可以复用http的端口与功能,除此外,他们没有其他的联系,而是完全是独立的协议,通常情况下,http是单向的web
服务,而websocket是全双工的,服务器和客户端可以实时的传输信息,在引用时他们可以在http服务器上同时部署,特别是在NodeJs中。
WebSocket与Socket
那么websocket和socket是什么关系呢?
其实可以理解为websocket是在socket的基础上实现的,其基于消息帧和TCP协议,而socket更通用,在编程中,可以选在tcp,udp,也需要自己控制数据流格式,每次的数据的长度都需要自己控制与读取。
Unity3d下如何使用WebSocket
现在越来越多的Unity3d游戏需要使用websocket或者后台的服务,在实际中,NodeJs,SocketIO越来越多的作为后台的服务加以应用,那么在unity3d的前端上可以使用的开源的websocket有两种:
UnitySocketIO
可以参考https://github.com/kaistseo/UnitySocketIO-WebSocketSharp ,其完全是C# dll的方式Unity3d中使用,测试了在windows和Linux下使用完全没有问题。分析一下优缺点:
优点: 直接使用dll,无unity3d的依赖,代码比较好测试,支持多种消息类型,如文本,Json等。
缺点:需要依赖第三方的库,如SuperSocket,SimpleJson等,在iOS下需要单独维护。
Socket.IO for unity
unity3d 的Asset store上有一个免费的开源项目 Socket.IO for unity (https://www.assetstore.unity3d.com/en/#!/content/21721)可以使用。测试了windows和linux版本,没有问题。 其他的andriod和ios应该也没有问题,根据代码和文档。
优点: 代码直接嵌入到Unity3d中,有所有的源代码,支持Json的消息传输。
缺点: 写测试用例相对繁琐,Json消息简单,不支持对象的Json解析,不过这块应该可以重写。http://blog.csdn.net/leoleocs/article/details/48824921
-
websocket python unity_Unity3D使用WebSocket通信相关实现
2021-01-30 14:07:17UNITY_WEBGL || UNITY_EDITOR if (ws.InternalRequest.Response != null) errorMsg= string.Format("Status Code from Server: {0} and Message: {1}", ws.InternalRequest.Response.StatusCode, ws.InternalRequest...///
///--------------------这是需要连接的URL地址///
public string url = "ws://localhost:8080//websocket/";privateWebSocket webSocket;private voidInit()
{
webSocket= new WebSocket(newUri(url));
webSocket.OnOpen+=OnOpen;
webSocket.OnMessage+=OnMessageReceived;
webSocket.OnError+=OnError;
webSocket.OnClosed+=OnClosed;
}private voidAntiInit()
{
webSocket.OnOpen= null;
webSocket.OnMessage= null;
webSocket.OnError= null;
webSocket.OnClosed= null;
webSocket= null;
}public voidConnect()
{
webSocket.Open();
print("发送连接");
}private byte[] getBytes(stringmessage)
{byte[] buffer =Encoding.Default.GetBytes(message);returnbuffer;
}public void Send(stringstr)
{
webSocket.Send(str);
}public voidClose()
{
webSocket.Close();
}voidOnOpen(WebSocket ws)
{
Debug.Log("连接成功");
}///
///接收信息///
///
/// 接收内容
void OnMessageReceived(WebSocket ws,stringmsg)
{
Debug.Log(msg);
SetLog(msg);
}///
///关闭连接///
void OnClosed(WebSocket ws, UInt16 code, stringmessage)
{
Debug.Log(message);
setConsoleMsg(message);
antiInit();
init();
}private voidOnDestroy()
{if (webSocket != null &&webSocket.IsOpen)
{
webSocket.Close();
antiInit();
}
}///
///Called when an error occured on client side///
voidOnError(WebSocket ws, Exception ex)
{string errorMsg = string.Empty;#if !UNITY_WEBGL || UNITY_EDITOR
if (ws.InternalRequest.Response != null)
errorMsg= string.Format("Status Code from Server: {0} and Message: {1}", ws.InternalRequest.Response.StatusCode, ws.InternalRequest.Response.Message);#endifDebug.Log(errorMsg);
setConsoleMsg(errorMsg);
antiInit();
init();
}
-
websocket python unity_Unity 连接WebSocket(ws://)服务器
2021-03-07 07:45:02Unity 连接ws,不用任何插件,忙活了一天终于搞定了,一直连接不上,原来是没有添加header,代码比较简单,直接贴出来普度众生using System;using System.Net.WebSockets;using System.Text;using System.Threading;...Unity 连接ws,不用任何插件,忙活了一天终于搞定了,一直连接不上,原来是没有添加header,
代码比较简单,直接贴出来普度众生
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
private void Start()
{
WebSocket();
}
public async void WebSocket()
{
try
{
ClientWebSocket ws = new ClientWebSocket();
CancellationToken ct = new CancellationToken();
//添加header
//ws.Options.SetRequestHeader("X-Token", "eyJhbGciOiJIUzI1N");
Uri url = new Uri("ws://121.40.165.18:8800/v1/test/test");
await ws.ConnectAsync(url, ct);
await ws.SendAsync(new ArraySegment(Encoding.UTF8.GetBytes("hello")), WebSocketMessageType.Binary, true, ct); //发送数据
while (true)
{
var result = new byte[1024];
await ws.ReceiveAsync(new ArraySegment(result), new CancellationToken());//接受数据
var str = Encoding.UTF8.GetString(result, 0, result.Length);
Debug.Log(str);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
-
websocket python unity_Unity3d 下websocket的使用-阿里云开发者社区
2020-12-11 11:26:44今天介绍一下如何在Unity3D下使用WebSocket。首先介绍一下什么是websocket,以及与socket,和http的区别与联系,然后介绍一下websocket的一些开源的项目。WebSocket是什么WebSocket协议是为了实现网络客户端和服务器... -
websocket python unity_基于SuperSocket实现的WebSocket服务器和Unity中使用Websocket
2020-12-11 11:26:43#endregion #region Unity Events void OnDestroy() { if (webSocket != null) webSocket.Close(); } void OnGUI() { scrollPos = GUILayout.BeginScrollView(scrollPos); GUILayout.Label(Text); GUILayout.... -
websocket python unity_u3d:使用websocket最简单的测试通信
2020-12-11 11:26:44UNITY_WEBGL || UNITY_EDITOR if (ws.InternalRequest.Response != null) errorMsg= string.Format("Status Code from Server: {0} and Message: {1}", ws.InternalRequest.Response.StatusCode, ws.InternalRequest... -
websocket python unity_【unity WebGL Websocket实时通信技术】-教程分享-【游戏蛮牛】-游戏出海,ar增强...
2020-12-11 11:26:44马上注册,结交更多好友,享用更多功能,...您需要 登录 才可以下载或查看,没有帐号?...unity5版本以后开始支持发布WebGL运行在html5中,彻底改变了无插件在网页中可以运行web3d,Websocket技术的出现也给unitywebGL... -
python和unity通信_socket——python和unity之间传输Json数据
2020-12-24 13:16:58做实验室的项目,使用socket在python和unity之间传输json数据,遇到了不少坑。python程序之间以及C#程序之间的socket通信先讲讲两个python之间的socket通信,不得不赞叹python写代码简直舒服,估计以后写代码会经常... -
Python to Unity
2020-12-09 02:06:34So my question is that using your stuff can I directly run python code to Unity and how we can build dll files directly from Python? </p><p>该提问来源于开源项目:off99555/Unity3D-Python-... -
unity python_Unity引擎内嵌python
2020-12-09 12:33:47Unity脚本using System.Collections;using System;using System.Collections.Generic;using UnityEngine;using System.Diagnostics; //需要添加这个名词空间,调用DataReceivedEventArgpublic class LoadPython : ... -
python语言unity3d_Unity3D 中的 IronPython
2020-11-28 19:13:01我想用IronPython作为Unity的外部语言脚本。IronPython执行加载所需的DLL放在Assets\Plugins。然而,当我运行脚本的时候出现了如下错误:PythonImportErrorException: No module named UnityEngineIronPython.... -
Unity3D-Python:在Unityy里使用Python脚本-源码
2021-02-06 06:30:13Unity3D-Python编辑器 在unity3d里使用python unity版本5.6.1 注意 我这是用@cesardeazevedo那里弄到的,然后我精简了一下,现在只需要放置一下就可以用了。操作如下:在游戏物体上绑定PyRun.cs在PyRun.cs上绑定Py... -
Python in Unity
2015-04-21 08:27:00http://stackoverflow.com/questions/11766181/ironpython-in-unity3d 转载于:https://www.cnblogs.com/lilei9110/p/4443290.html -
python和unity3d_纠结学习Python还是unity3d_课课家教育
2020-12-03 23:55:35在线客服QQ:3315713922 相关推荐 unity3d游戏开发实战视频教程 unity3d实战教程之王牌飞机大战 软件测试之Python Selenium3软件自动化测试项目实战视频教程 版权声明:本文为博主原创文章,未经博主允许不得转载。 -
unity和python通讯_Python 与 Unity mlagents 交互 API
2020-12-03 23:55:05初始化 unity 环境12345import numpy as npimport matplotlib.pyplot as pltfrom mlagents.envs import UnityEnvironment%matplotlib inline初始化环境 env = UnityEnvironment(file_name="3DBall", worker_id=0, ... -
python语言unity3d_Unity3d 5.x的最简Python服务器
2020-12-01 12:03:52在我试图通过Unity5.xNetworkTransport LLAPI和Python3.x套接字模块从Unity3D游戏客户端获得低级调用和响应目标:将发送到服务器的消息反弹回客户端。在问题:当我运行Unity3d客户机时,套接字打开,服务器每秒打印... -
python+unity表情驱动一
2021-02-26 13:20:34python+unity表情驱动工具一引言python代码 引言 最近看到一个视频关于python控制unity人物表情的视频,大体思路是使用python控制摄像头进行人脸识别,识别68个关键点,再将识别后的数据通过本地端口传递给unity,... -
内嵌python_Unity引擎内嵌python
2021-01-12 02:39:02Unity脚本using System.Collections;using System;using System.Collections.Generic;using UnityEngine;using System.Diagnostics; //需要添加这个名词空间,调用DataReceivedEventArg public class LoadPython : ... -
unity和python通讯_Unity 与 Python 实现TCP通讯
2020-12-03 23:55:41前言:由于最近在做一个项目,要使用到python和Unity 进行TCP通讯,这里介绍以Python端为Server,unity端为Client的例子。Server:服务端使用的是PyQt中的QTcpServer,用Qt的机制可以实现比较高的效率。代码如下:#... -
python与unity_Python套接字服务器和C#Unity客户端
2020-12-15 14:44:54我们正在尝试将Python服务器与套接字连接而不阻塞TCP . 我们尝试与其他客户一起工作,就像一个魅力 .server = MyTCPServer((ip_localhost, port), MyTCPServerHandler)server.socket.setblocking(0)在另一方面,我们... -
python scratch unity_Unity3D入门其实很简单
2020-12-16 18:59:00在上次发布拙作后,有不少童鞋询问本人如何学习Unity3D。本人自知作为一名刚入门的菜鸟,实在没有资格谈论这么高大上的话题,生怕误导了各位。不过思来想去,决定还是写一些自己的经验,如果能给想要入门U3D的您一些... -
python语言unity3d_是否可以在Unity3D中使用python进行控制台开发?
2021-01-30 02:52:57我正在Unity3D中开发一个3D图形计算器软件,我正在努力寻找用C/C编写的好的数值/符号数学库。另外,我想让计算器可编程(就像学校里每个人都用的TI-84计算器)。在我发现Python对于这个项目的主干来说是一种非常好的... -
python和unity通信_使用websocket连接Unity(客户端)和Python(服务器)
2021-01-14 09:11:30我做了一个程序,允许我每次在unity中按空格键时发送一条消息,并使用cherrpy将其发送到python服务器。在问题是我的websocket.py'成功地服务于本地主机如下,一旦我启动团结播放器,它只是立即关闭与错误。希望有人...