Skip to content

Commit

Permalink
完善代码注释,完善变量名,修改帮助文档Readme
Browse files Browse the repository at this point in the history
  • Loading branch information
yinlong committed Sep 10, 2018
1 parent 86598bd commit 7e263db
Show file tree
Hide file tree
Showing 5 changed files with 65 additions and 69 deletions.
42 changes: 29 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,34 +4,41 @@

# UnityWebSocket 使用

### 1. [最新版本下载](https://github.com/y85171642/UnityWebSocket/releases/latest)
### 1. [最新版本下载](https://github.com/y85171642/UnityWebSocket/releases)

### 2. 使用方法:
- 导入 UnityWebSocket.unitypackage

- 创建WebSocket实例

```csharp
// 命名空间
using UnityWebSocket;

// 创建实例
string address = "ws://127.0.0.1:8730/test";
WebSocket scoket = new WebSocket(address);

// 注册回调
scoket.onOpen += OnOpen;
scoket.onClose += OnClose;
scoket.onReceive += OnReceive;
scoket.onMessage += OnMessage;
socket.onError += OnError;

// 连接
socket.Connect();

// 发送数据
socket.Send(data);//发送数据类型byte[]
socket.Send(str); // 发送类型String数据
socket.Send(bytes); // 发送byte[]类型数据
// 关闭连接
socket.Close();
```

### 3. 功能说明
- 详细使用方法可参考项目中的Example示例,或参考 [websocket-sharp](https://github.com/sta/websocket-sharp) 的使用方法。
### 3. 模块说明
- WebSocket.jslib

路径:Plugins/WebSocketJS/WebSocketJS.jslib
Expand All @@ -40,27 +47,28 @@
- WebSocket.cs

作用:WebSocket连接,可同时创建多个不同连接。
已经支持全平台使用。

- WebSocketReceiver.cs

作用:与jslib交互,负责收发多个WebSocket消息。
该脚本在使用WebSocket时会自动加载到场景中,并添加为DonDestroyOnLoad
该脚本在使用WebSocket时会自动加载到场景中,并添加到DonDestroyOnLoad

- Demo场景
- Example场景

作用:WebSocket的使用方法示例。

### 4. 注意(Warning)
- WebSocket的命名空间是 UnityWebSocket 不要用错了 :) 。
- WebSocketonOpenOnCloseOnReceive 回调都发生在网络线程中,回调处理函数不能直接修改主线程中的Unity组件内容,需要在主线程中加消息处理队列,缓存网络消息后,再在主线程中处理消息包。
- WebGL平台下,需要发布到Tomcat等服务器上运行。
- ServerDemo 是用于Demo测试版本的WebSocket服务器,兼容所有Release版本的Demo
- v1.1 后版本有使用websocket-sharp插件,如果本地已使用该插件,可自行修改或删除。
- WebSocket的命名空间是 UnityWebSocket ,项目中有多个命名空间存在WebSocket类,不要用错了 :) 。
- WebSocketonOpenOnCloseOnMessageOnError 回调都发生在网络线程中,回调处理函数不能直接修改主线程中的Unity组件内容,需要在主线程中加消息处理队列(需要加锁),缓存网络消息后,再在主线程中处理消息包。
- WebGL平台下,暂时不能使用异步连接、关闭、发送,接口仍然使用的同步方式。
- WebGL平台下,需要将打包好的文件,发布到Tomcat等服务器上运行。
- ServerDemo 是用于示例版本的WebSocket测试服务器,需要使用对应的版本。
- v1.1 后版本加入了websocket-sharp插件(源码),如果你的项目已包含该插件,可自行删除或修改。

### 5. WebSocket服务器
- 项目发布完成后,需要一个WebSocket服务器收发消息,以下是Demo版本对应的服务器。
- [服务器Demo下载](https://github.com/y85171642/UnityWebSocket/tree/master/Release/Server)
- 提供简单的WebSocket消息收发
- 每个版本都包含对应的服务器(ServerDemo)。
- 使用了开源项目 [websocket-sharp](https://github.com/sta/websocket-sharp)
### 6. 版本记录
Expand All @@ -78,3 +86,11 @@
- 完善项目命名空间,目录结构。
- WebSocket增加异步连接发送方法。(webgl平台下仍调用同步方式)
- 添加开发分支,git管理方式调整。

#### v1.2
- 重构代码,规范代码,模块整理。
- 规范接口,参考websocket-sharp结构,使用EventHandler方式处理事件。
- 添加了字符串数据收发的支持。
- jslib中添加了获取socket.readyState的方法。
- jslib中的SendMessage参数整理。
- fix some Bugs.
31 changes: 15 additions & 16 deletions UnityWebSocket/Assets/Plugins/WebSocketJS/WebSocketJS.jslib
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

var WebSocketJS =
{
$RECEIVER_NAME: {},
Expand Down Expand Up @@ -55,7 +54,8 @@
webSocket.onerror = function(e)
{
// can not catch the error reason, only use for debug.
OnError(address, e.message);
// see this page https://stackoverflow.com/questions/18803971/websocket-onerror-how-to-read-error-description
OnError(address, "a websocket error occured.");
};

webSocketMap.set(address, webSocket);
Expand All @@ -68,7 +68,7 @@
if(webSocketMap.has(address))
webSocketMap.get(address).send(HEAPU8.buffer.slice(msgPtr, msgPtr + length));
else
OnError(address, "send msg with a WebSocket not Instantiated");
OnError(address, "send msg binary with a WebSocket not Instantiated");
},

// call by unity
Expand All @@ -79,7 +79,7 @@
if(webSocketMap.has(address))
webSocketMap.get(address).send(msg);
else
OnError(address, "send msg with a WebSocket not Instantiated");
OnError(address, "send msg string with a WebSocket not Instantiated");
},

// call by unity
Expand All @@ -105,32 +105,30 @@

$OnMessage: function(address, opcode, data)
{
var addr_opcode_data = address + "_" + opcode + "_";
// blobData
if(opcode == 2)
var combinedMsg = address + "_" + opcode + "_";
if(opcode == 2) // blob data
{
var reader = new FileReader();
reader.addEventListener("loadend", function()
{
// format : address_data, (address and data split with "_")
// the data format is hex string
// data format to hex string
var array = new Uint8Array(reader.result);
for(var i = 0; i < array.length; i++)
{
var b = array[i];
if(b < 16)
addr_opcode_data += "0" + b.toString(16);
combinedMsg += "0" + b.toString(16);
else
addr_opcode_data += b.toString(16);
combinedMsg += b.toString(16);
}
SendMessage(RECEIVER_NAME, MESSAGE_METHOD_NAME, addr_opcode_data);
SendMessage(RECEIVER_NAME, MESSAGE_METHOD_NAME, combinedMsg);
});
reader.readAsArrayBuffer(data);
}
else
else // string data
{
addr_opcode_data += data;
SendMessage(RECEIVER_NAME, MESSAGE_METHOD_NAME, addr_opcode_data);
combinedMsg += data;
SendMessage(RECEIVER_NAME, MESSAGE_METHOD_NAME, combinedMsg);
}
},

Expand All @@ -143,7 +141,8 @@
{
if(webSocketMap.get(address))
webSocketMap.delete(address);
SendMessage(RECEIVER_NAME, CLOSE_METHOD_NAME, address+"_"+code+"_"+reason+"_"+wasClean);
var combinedMsg = address + "_" + code + "_" + reason + "_" + wasClean;
SendMessage(RECEIVER_NAME, CLOSE_METHOD_NAME, combinedMsg);
},

$OnError: function(address, errorMsg)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ RenderSettings:
m_ReflectionIntensity: 1
m_CustomReflection: {fileID: 0}
m_Sun: {fileID: 0}
m_IndirectSpecularColor: {r: 0.37311947, g: 0.38074005, b: 0.35872722, a: 1}
m_IndirectSpecularColor: {r: 0.37311953, g: 0.38074014, b: 0.3587274, a: 1}
--- !u!157 &3
LightmapSettings:
m_ObjectHideFlags: 0
Expand Down Expand Up @@ -682,7 +682,7 @@ GameObject:
m_Component:
- component: {fileID: 313235359}
m_Layer: 5
m_Name: log
m_Name: messageBox
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
Expand Down Expand Up @@ -2274,7 +2274,7 @@ GameObject:
- component: {fileID: 1002391569}
- component: {fileID: 1002391568}
m_Layer: 5
m_Name: bg
m_Name: mask
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
Expand Down Expand Up @@ -2847,9 +2847,9 @@ MonoBehaviour:
entryTemplate: {fileID: 1967433805}
currentSelectBg: {fileID: 1869076092}
currentSelectText: {fileID: 533606997}
logPanel: {fileID: 313235358}
logText: {fileID: 401804344}
logPanelCloseBtn: {fileID: 571569540}
messageBoxObj: {fileID: 313235358}
messagexBoxText: {fileID: 401804344}
messageBoxCloseBtn: {fileID: 571569540}
--- !u!4 &1541134461
Transform:
m_ObjectHideFlags: 0
Expand Down Expand Up @@ -3482,7 +3482,7 @@ Canvas:
m_OverrideSorting: 0
m_OverridePixelPerfect: 0
m_SortingBucketNormalizedSize: 0
m_AdditionalShaderChannelsFlag: 25
m_AdditionalShaderChannelsFlag: 0
m_SortingLayerID: 0
m_SortingOrder: 0
m_TargetDisplay: 0
Expand Down Expand Up @@ -3718,7 +3718,7 @@ MonoBehaviour:
m_HandleRect: {fileID: 837294421}
m_Direction: 2
m_Value: 1
m_Size: 0.99999994
m_Size: 1
m_NumberOfSteps: 0
m_OnValueChanged:
m_PersistentCalls:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@ public class TestWebSocket : MonoBehaviour
public Image currentSelectBg;
public Text currentSelectText;

public GameObject logPanel;
public Text logText;
public Button logPanelCloseBtn;
public GameObject messageBoxObj;
public Text messagexBoxText;
public Button messageBoxCloseBtn;

private Dictionary<string, WebSocketEntry> m_sockets = new Dictionary<string, WebSocketEntry>();
private WebSocketEntry m_selectedEntry;
Expand All @@ -32,17 +32,17 @@ private void Awake()
connentBtn.onClick.AddListener(Connect);
closeBtn.onClick.AddListener(Close);
sendBtn.onClick.AddListener(Send);
logPanelCloseBtn.onClick.AddListener(OnClickCloseLog);
messageBoxCloseBtn.onClick.AddListener(OnClickCloseMessageBox);
entryTemplate.gameObject.SetActive(false);
logPanel.gameObject.SetActive(false);
messageBoxObj.gameObject.SetActive(false);
}

public void NewSocket()
{
string addr = addressInput.text;
if (m_sockets.ContainsKey(addr))
{
Log("Duplicate address " + addr);
MessageBox("Duplicate address " + addr);
return;
}

Expand Down Expand Up @@ -73,7 +73,6 @@ public void Connect()

public void Close()
{

if (m_selectedEntry == null)
return;
m_selectedEntry.Close();
Expand All @@ -86,15 +85,15 @@ public void Send()
m_selectedEntry.Send(messageInput.text);
}

public void Log(string log)
public void MessageBox(string log)
{
logPanel.SetActive(true);
logText.text = log;
messageBoxObj.SetActive(true);
messagexBoxText.text = log;
}

private void OnClickCloseLog()
private void OnClickCloseMessageBox()
{
logPanel.SetActive(false);
messageBoxObj.SetActive(false);
}

void Update()
Expand Down Expand Up @@ -195,25 +194,7 @@ private void OnError(object sender, ErrorEventArgs e)
{
content += "[ERROR] " + e.Message + "\n";
}


Vector3[] CreatePoint(Vector3 start, Vector3 end, float distance)
{
Vector3[] retPoint = new Vector3[4];

Vector3 v3 = Vector3.Cross(end - start, Vector3.up);

retPoint[0] = start + v3 * distance;
retPoint[1] = start - v3 * distance;
retPoint[3] = end + v3 * distance;
retPoint[2] = end - v3 * distance;

return retPoint;
}

}


}


Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public void RemoveListener(string address)
/// <summary>
/// jslib will call this method on message received.
/// </summary>
/// <param name="address_data">address_opcode_data(hex string)</param>
/// <param name="address_opcode_data">address_opcode_data(hex string)</param>
private void OnMessage(string address_opcode_data)
{
string[] sp;
Expand Down Expand Up @@ -100,7 +100,7 @@ private void OnOpen(string address)
/// <summary>
/// jslib will call this method on connection closed.
/// </summary>
/// <param name="address">address</param>
/// <param name="address_code_reason_wasClean">address_code_reason_wasClean</param>
private void OnClose(string address_code_reason_wasClean)
{
string[] sp;
Expand Down

0 comments on commit 7e263db

Please sign in to comment.