直接上代码,如下
完整工程下载
https://download.csdn.net/download/weicaijiang/12649923
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Linq;
using System.Threading;
//using WebSocket4Net;
using BestHTTP;
using BestHTTP.WebSocket;
public class WebsocketCsharp {
// ws://demos.kaazing.com/echo
// ws://echo.websocket.org/
string url = "ws://echo.websocket.org/";
WebSocket websocket;
// Use this for initialization
void Start () {
//initWebsocket();
}
// Update is called once per frame
void Update () {
}
public void initWebsocket()
{
Debug.Log("init websocket url:"+url);
websocket = new WebSocket(new Uri(url));
websocket.OnOpen += onOpened;
websocket.OnMessage += onMessageReceived;
websocket.OnError += onError;
websocket.OnClosed += onClosed;
websocket.Open();//开始
}
void onOpened(WebSocket ws)
{
Debug.Log("onOpened");
websocket.Send(Time.time + "");
}
void onMessageReceived(WebSocket ws, string msg)
{
Debug.Log("onMessageReceived:"+msg);
}
void onClosed(WebSocket ws, UInt16 code, string msg)
{
Debug.Log("onClosed:"+msg);
}
void onError(WebSocket ws, Exception e)
{
Debug.Log("onError:"+e.Message);
}
public void send(string str)
{
Debug.Log("send:" + str);
websocket.Send(str);
}
}