1.安装node。https://nodejs.org/en/
2.安装ws模块
ws:是nodejs的一个WebSocket库,可以用来创建服务。 https://github.com/websockets/ws
nmp install ws
或者全局 npm install ws -g
3.server.js
在项目里面新建一个server.js,创建服务,指定8181端口,将收到的消息log出来。
var WebSocketServer = require('ws').Server;//引入模块
wss = new WebSocketServer({ port: 8181 });//创建一个WebSocketServer的实例,监听端口8181
wss.on('connection', function (ws) {
console.log('client connected');
ws.on('message', function (message) {
console.log(message);
ws.send('Hi Client');
//ws.send('Hi 刘文倩');
ws.send('Hi 刘文倩');
});//当收到消息时,在控制台打印出来,并回复一条信息
});
4、使用Unity3D做为WebSocket客户端,主要是使用了一个插件BestHttp
5、编写C#脚本
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://192.168.10.9:3000";
public string url = "ws://localhost:8181";
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.addEventListener = 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
/// <summary>
/// Called when the web socket is open, and we are ready to send and receive data
/// </summary>
void OnOpen(WebSocket ws)
{
Debug.Log("connected");
setConsoleMsg("Connected");
}
/// <summary>
/// Called when we received a text message from the server
/// </summary>
void OnMessageReceived(WebSocket ws, string message)
{
Debug.Log(message);
setConsoleMsg(message);
}
/// <summary>
/// Called when the web socket closed
/// </summary>
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();
}
}
/// <summary>
/// Called when an error occured on client side
/// </summary>
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
}
6、启动服务器与unity客户端
绘制UI层链接到指定函数
连接成功