Send() public method

public Send ( byte buffer ) : void
buffer byte
return void
Ejemplo n.º 1
0
        public bool SendDataFields(string[] dataFields)
        {
            if (dataFields == null || dataFields.Length == 0)
            {
                LastError = "no data field set";
                return(false);
            }

            var obj = new JObject
            {
                ["mode"] = "register",
                ["enableLocomotives"] = dataFields.Contains("enableLocomotives"),
                ["enableAccessories"] = dataFields.Contains("enableAccessories"),
                ["enableS88"]         = dataFields.Contains("enableS88")
            };

            try
            {
                _ws?.Send(obj.ToString(Formatting.Indented));

                return(true);
            }
            catch (Exception ex)
            {
                LastError = ex.Message;
                return(false);
            }
        }
Ejemplo n.º 2
0
        private void SendSubscribeOperation(ROSBridgeSubscriber subscriber)
        {
            string s = ROSBridgeMsg.Subscribe(subscriber.Topic, ((IMsg)Activator.CreateInstance(subscriber.MessageType)).ROSMessageType);

            Debug.Log($"Sending: {s}");
            _ws?.Send(s);
        }
Ejemplo n.º 3
0
        private static async Task Ping()
        {
            while (ws != null && ws.IsAlive)
            {
                if (Exited)
                {
                    PingerActive = false;
                    return;
                }

                if (Pinged)
                {
                    PingerActive = false;
                    ws?.Close();
                    return;
                }

                Pinged = true;

#if DEBUG
                Log.Info(">b");
#endif
                ws?.Send("b");

                await Task.Delay(10000);
            }

            PingerActive = false;

            if (!CreatingClient)
            {
                CreateConnection(1000);
            }
        }
Ejemplo n.º 4
0
        public void SendChatMessage(string message)
        {
            var msg = new MessageChatMessage()
            {
                Username = Username,
                Message  = message
            };

            socket?.Send(JsonConvert.SerializeObject(msg));
        }
Ejemplo n.º 5
0
        private void PublicAPI_Load(object sender, EventArgs e)
        {
            if (socket != null)
            {
                socket.OnDataPairs        += Socket_OnDataPairs;
                socket.OnDataPairsDetail  += Socket_OnDataPairsDetail;
                socket.OnDataOrderbook    += Socket_OnDataOrderbook;
                socket.OnDataRecentTrades += Socket_OnDataRecentTrades;
                socket.OnDataLastPrice    += Socket_OnDataLastPrice;
                socket.OnDataPriceByTime  += Socket_OnDataPriceByTime;

                // get market data
                socket?.Send(Subs.Pairs(SubsType.GetExist));
            }
        }
Ejemplo n.º 6
0
        public void Play()
        {
            var uri = new Uri(Server + "?user="******"Something strange is happening on the server... Response:\n{0}", response);
                        ShouldExit = true;
                    }
                    else
                    {
                        var boardString = response.Substring(ResponsePrefix.Length);

                        var action = DoMove(new GameBoard(boardString));

                        socket.Send(action);
                    }
                }
            }
        }
Ejemplo n.º 7
0
 internal void Send(string message)
 {
     if (IsConnected)
     {
         Log.Info(Constants.LOG_NAME, $"Sending: {message}");
         _websocket?.Send(message);
     }
 }
Ejemplo n.º 8
0
        protected override void SocketOnOpen(object sender, EventArgs e)
        {
            base.SocketOnOpen(sender, e);

            var encodedQuery = LZStringCSharp.LZString.CompressToUTF16(_query);

            WebSocket?.Send(encodedQuery);
        }
Ejemplo n.º 9
0
    public void Send(string msg)
    {
        if (IsConnect())
        {
            Debug.Log("[ws] Send : " + msg);

            ws?.Send(msg);
        }
    }
Ejemplo n.º 10
0
    //network
    public static void ConnectToServer()
    {
        Game.GameState = Game.GameStateType.ConnectedToServer;

        ws = new WebSocket("ws://127.0.0.1:8080", "echo-protocol");		//production: ws://ec2-54-227-104-51.compute-1.amazonaws.com:8080/

        ws.OnOpen += (sender, e) =>
        {
            Debug.Log("connection with server opened");
            if (ServerConnect != null) ServerConnect();
            Loom.QueueOnMainThread(()=>{
                ws.Send( JsonConvert.SerializeObject( new NetworkMsg(){ type = "connectRequest" }) );
            });
        };

        ws.OnMessage += delegate(object sender, MessageEventArgs e) {
            NetworkMsg ms = JsonConvert.DeserializeObject<NetworkMsg>(e.Data);
            //Debug.Log("from: " + ms.id + " type: " +  ms.type + " tata: " + ms.msg);
            if (ServerMsg != null) ServerMsg(ms);
        };

        ws.OnError += delegate(object sender, ErrorEventArgs e) {
            Debug.Log("error: " + e.Message);
            if (ServerError!=null) ServerError();
        };

        ws.OnClose += delegate(object sender, CloseEventArgs e) {
            Debug.Log("connection closed: " + e.Data);
            if (ServerDisonnect!=null) ServerDisonnect();
        };

        ws.OnOpen+= delegate(object sender, System.EventArgs e) {
        };

        #if DEBUG
        ws.Log.Level = LogLevel.TRACE;
        #endif

        ws.Connect();
    }
Ejemplo n.º 11
0
        public WebSocketEndpoint()
        {
            var websocket = new WebSocket("ws://24.87.140.2:4000/", "basic");

            websocket.OnOpen += (sender, args) =>
                                    {
                                        m_OpenEvent.Set();
                return;
            };
            websocket.OnClose += (sender, args) =>
            {
                return;
            };
            websocket.OnMessage += (sender, args) =>
                                       {
                                           return;
                                       };

            websocket.Connect();

            m_OpenEvent.WaitOne(1000);
            websocket.Send("authenticate a b c");
        }
Ejemplo n.º 12
0
	public WsClient () {

		bool success = TestConnection();
		if (success) {
			Debug.Log ("Server check ok");
			string server = String.Format("wss://{0}:{1}/",  ip,  port );
			using (conn = new WebSocket (server,"game"));
			conn.Connect ();

			conn.OnOpen += (sender, e) => conn.Send ("Server Connected");

			conn.OnError += (sender, e) => {
				Debug.Log("Websocket Error");
				conn.Close ();
			};

			conn.OnClose += (sender, e) => {
				Debug.Log("Websocket Close");
				conn.Close ();
			};
		} else {
			Debug.Log ("Server check failed");
			return;
		}

		conn.SslConfiguration.ServerCertificateValidationCallback =
			(sender, certificate, chain, sslPolicyErrors) => {
			// Do something to validate the server certificate.
			Debug.Log ("Cert: " + certificate);

			return true; // If the server certificate is valid.
		};



	}
Ejemplo n.º 13
0
        public static void ConnectToWebSocket()
        {
            WebSocket mySocket = new WebSocket();
            mySocket.OpenEvent += new OpenEventHandler((object sender, OpenEventArgs e) =>
            {
                Console.WriteLine("Open Event");
                mySocket.Send("Hello, World");
            });

            mySocket.MessageEvent += new MessageEventHandler((object sender,
            MessageEventArgs e) =>
            {
                Console.WriteLine(e.Data);
            });

            mySocket.CloseEvent += new CloseEventHandler((object sender, CloseEventArgs e) =>
            {
                Console.WriteLine("Close Event");
            });

            mySocket.Connect("ws://localhost:8001/echo");

            //mySocket.Close();
        }
Ejemplo n.º 14
0
        private void ThreadDequeuSendMessages(object parameter)
        {
            var queue = parameter as LockedQueue <Request>;

            while (SendFromThread)
            {
                if (IsConnected)
                {
                    if (!queue.IsEmpty)
                    {
                        var message = queue.Dequeue();
                        if (!message.IsNull())
                        {
                            webSocket?.Send(message.ToString());
                        }
                    }
                }
                else
                {
                    connectionOpenEvent.WaitOne(2000); // wait connect signal or wait 2 sec
                }
            }
            CustomTools.Console.DebugLog("Client::ThreadDequeuSendMessages() Thread done");
        }
Ejemplo n.º 15
0
 private void WSSend(string data)
 {
     Console.WriteLine("SEND: " + data);
     wsclient?.Send(data);
 }
Ejemplo n.º 16
0
        public async void SendMessage(string message)
        {
            Console.WriteLine($"Networking: MSG:\n{message}");

            socket?.Send(message);
        }
        /// <summary>
        /// Subscribes to the provided <paramref name="outgoing"/> stream, sending all events to the provided <paramref name="socket"/>.
        /// </summary>
        /// <param name="outgoing">The outgoing stream.</param>
        /// <param name="socket">
        /// The socket.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/> which will complete when either the observable completes (or errors) or the socket is closed (or errors).
        /// </returns>
        private static async Task OutgoingMessagePump(IObservable<string> outgoing, WebSocket socket)
        {
            var completion = new TaskCompletionSource<int>();
            var subscription = new IDisposable[] { null };

            Action complete = () =>
            {
                subscription[0]?.Dispose();
                completion.TrySetResult(0);
            };

            // Until the socket is closed, pipe messages to it, then complete.
            subscription[0] = outgoing.TakeWhile(_ => !socket.IsClosed).SelectMany(
                next => socket.Send(ResponseKind.Next + next).ToObservable(),
                error => socket.Send(ResponseKind.Error + JsonConvert.SerializeObject(error.ToDetailedString())).ToObservable(),
                () =>
                {
                    if (socket.IsClosed)
                    {
                        return Observable.Empty<Unit>();
                    }

                    // Send and close the socket.
                    var send = socket.Send(ResponseKind.Completed.ToString(CultureInfo.InvariantCulture)).ToObservable();
                    return send.SelectMany(_ => socket.Close((int)WebSocketCloseStatus.NormalClosure, "onCompleted").ToObservable());
                }).Subscribe(_ => { }, _ => complete(), complete);
            await completion.Task;
        }
Ejemplo n.º 18
0
 public void SendMessage(string data)
 {
     _webSocket?.Send(data);
 }
Ejemplo n.º 19
0
 public void WriteByte(byte data)
 {
     websocket.Send(new byte[1] {
         data
     });
 }
Ejemplo n.º 20
0
 public void Send(string s)
 {
     _ws?.Send(s);
 }
Ejemplo n.º 21
0
 private void SendSubscribeTopic(byte[] byts)
 {
     websocket.Send(byts, 0, byts.Length);
 }
Ejemplo n.º 22
0
        internal override void PostToSocket(TheDeviceMessage pMsg, byte[] pPostBuffer, bool PostAsBinary, bool IsInitialConnect)
        {
            TheDiagnostics.SetThreadName("WSPostToSocketCSWS:" + (MyQSender.MyTargetNodeChannel?.ToString() ?? "DEAD"));

            if (MyQSender != null && !MyQSender.IsConnected && !IsInitialConnect)
            {
                Shutdown(true, "1653:QSenderCSWS not connected but Posting in illegal state");
                return;
            }

            if (!ProcessingAllowed)         //NEW:V3BETA2: New Waiting Algorythm
                WaitUntilProcessingAllowed();

            if (!IsActive || !TheBaseAssets.MasterSwitch)
                return;

            if (websocket == null && webSocketSession==null)
            {
                eventClosed?.Invoke("1654:WebSockets are down");
                return;
            }
            ProcessingAllowed = false;

            try
            {
                if (pPostBuffer != null)
                {
                    TheCDEKPIs.IncrementKPI(eKPINames.QKBSent, pPostBuffer.Length);
                    if (PostAsBinary)
                    {
                        if (webSocketSession != null)
                            webSocketSession.SendB(pPostBuffer);
                        else
                        {
                            websocket?.Send(pPostBuffer);
                        }
                    }
                    else
                    {
                        if (webSocketSession != null)
                            webSocketSession.SendB(TheCommonUtils.CArray2UTF8String(pPostBuffer));
                        else
                        {
                            websocket?.Send(TheCommonUtils.CArray2UTF8String(pPostBuffer));
                        }
                    }
                }
                else
                {
                    string toSend = TheCommonUtils.SerializeObjectToJSONString(pMsg);
                    if (PostAsBinary)
                    {
                        byte[] toSendb = TheCommonUtils.CUTF8String2Array(toSend);
                        TheCDEKPIs.IncrementKPI(eKPINames.QKBSent, toSendb.Length);
                        if (webSocketSession != null)
                            webSocketSession.SendB(toSendb);
                        else
                        {
                            websocket?.Send(toSendb);
                        }
                    }
                    else
                    {
                        if (webSocketSession != null)
                            webSocketSession.SendB(toSend);
                        else
                        {
                            websocket?.Send(toSend);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Shutdown(true, "1655:DoPostToSocketCSWS had a fault: "+e);
            }

            if (mre != null)
                ProcessingAllowed = true;
        }
Ejemplo n.º 23
0
 static partial void Send(string data)
 {
     webSocket?.Send(data);
 }
Ejemplo n.º 24
0
 protected override void SocketOnOpen(object sender, EventArgs e)
 {
     base.SocketOnOpen(sender, e);
     WebSocket?.Send("{\"type\": \"version\", \"value\": 3}");
 }
Ejemplo n.º 25
0
 private static void ClientSocketGame_OnClose(object sender, CloseEventArgs e)
 {
     clientSocketGame.Send(Serializator.serialize(new NetPackett {
         messageType = MessageType.ExitGame
     }));
 }
 private void DisconnectSink(string error, WebSocket ws)
 {
     LogStreamerSession sink;
     if (_children.TryGetValue(ws.ToUInt64(), out sink))
     {
         sink.Quit(error);
         return;
     }
     ws.Send("!QUIT UnknownSocket");
     ws.Disconnect("Unknown socket");
 }
Ejemplo n.º 27
0
 private static void Send(string data)
 {
     NHLog.Info("NHWebSocket", $"Sending data: {data}");
     _webSocket?.Send(data);
 }
 /// <summary>
 /// Sends binary <paramref name="data"/> to the client on a session.
 /// </summary>
 /// <remarks>
 /// This method is available after the WebSocket connection has been established.
 /// </remarks>
 /// <param name="data">
 /// An array of <see cref="byte"/> that represents the binary data to send.
 /// </param>
 protected void Send(byte[] data)
 {
     _websocket?.Send(data);
 }
Ejemplo n.º 29
0
 public void SendCommand(string command)
 {
     _webSocketClient?.Send(command);
 }
Ejemplo n.º 30
0
 public void SendMessage(byte[] buffer)
 {
     WebSocket?.Send(buffer, 0, buffer.Length);
 }
 public void SendMessageToServer(string text)
 {
     _webSocketConnection?.Send(text);
 }
Ejemplo n.º 32
0
        internal static void StartServer()
        {
            Thread.Sleep(2000);

            ws?.CloseAsync();

            while (Queue.TryDequeue(out var _))
            {
            }

            Signal.Reset();

            ws             = null;
            CreatingClient = false;
            Exited         = false;

            CreateConnection();

            while (!Exited)
            {
                Signal.WaitOne();

                string message = null;

                while (Queue.TryDequeue(out message))
                {
                    try
                    {
                        if (message == "exit")
                        {
                            Exited = true;
                            ws?.Close();
                            break;
                        }

                        if (CreatingClient)
                        {
                            continue;
                        }
                        if (ws == null || !ws.IsAlive)
                        {
                            CreateConnection(1000);
                            continue;
                        }
#if DEBUG
                        Log.Info(">" + message);
#endif
                        ws?.Send(message);
                    }
                    catch (Exception e)
                    {
                        Log.Error(e);
                    }
                }

                Signal.Reset();
            }

            if (ws != null && ws.IsAlive)
            {
                ws.Close();
            }
        }
 private void websocket_Opened(object sender, EventArgs e)
 {
     Console.WriteLine("WebSocket connection open");
     websocket.Send(JsonUtils.serialize(new StatusRequestMessage()));
 }
Ejemplo n.º 34
0
 /// <summary>
 /// Send buffer asyncronoushly to websocket server
 /// </summary>
 /// <param name="buffer">data buffer</param>
 /// <returns></returns>
 public Task SendAsync(byte[] buffer)
 {
     return(Task.Run(() => { Socket.Send(buffer); }));
 }
Ejemplo n.º 35
0
        private void SocketConnection_OnMessage(object sender, MessageEventArgs e)
        {
            var ws = (WebSocket)sender;

            if (e.IsText)
            {
                ws.Log.Info("Text Message");
                WriteLog(e.Data);

                JObject baleObject = JObject.Parse(e.Data);
                var     mainType   = baleObject["$type"].Value <string>();
                var     subType    = "NO-BODY";
                var     date       = "NO-DATE";

                //detect body type
                if (baleObject["body"] != null && baleObject["body"]["$type"] != null)
                {
                    subType = baleObject["body"]["$type"].Value <string>();
                }

                //detect date main code
                if (baleObject["body"] != null && baleObject["body"]["date"] != null)
                {
                    date = baleObject["body"]["date"].Value <string>();
                }

                //detect date main code
                if (baleObject["body"] != null && baleObject["body"]["startDate"] != null)
                {
                    date = baleObject["body"]["startDate"].Value <string>();
                }

                //detect peer شناسایی کاربر
                if (baleObject["body"] != null && baleObject["body"]["peer"] != null)
                {
                    LastUser = new Peer()
                    {
                        accessHash = baleObject["body"]["peer"]["accessHash"].Value <string>(),
                        id         = baleObject["body"]["peer"]["id"].Value <string>(),
                        type       = baleObject["body"]["peer"]["$type"].Value <string>()
                    };

                    WriteLog("LastUserId:\t" + LastUser.id);
                }

                txtRec.Text += mainType + "\t" + subType + "\t" + date + "\r\n";

                //این یک پیام است
                if (mainType == "FatSeqUpdate" && subType == "Message")
                {
                    //این پیام متنی است
                    if (baleObject["body"]["message"]["$type"].Value <string>() == "Text")
                    {
                        var message = baleObject["body"]["message"]["text"].Value <string>();
                        txtRec.Text += message + "\r\n";

                        if (isFirstMessage)
                        {
                            isFirstMessage = false;
                            var welcomeSticker = SendMessageTools.GetStickerMessage(new SendSticker()
                            {
                                Type        = "Sticker",
                                FastPreview = null,
                                Image256    = new Model.Image()
                                {
                                    FileLocation = new FileLocation()
                                    {
                                        FileStorageVersion = 1,
                                        AccessHash         = "549755813890",
                                        FileId             = "7415072606480367873"
                                    },
                                    Height   = 256,
                                    Width    = 256,
                                    FileSize = 4924
                                },
                                Image512 = new Model.Image()
                                {
                                    FileLocation = new FileLocation()
                                    {
                                        FileStorageVersion = 1,
                                        AccessHash         = "549755813890",
                                        FileId             = "-8656471477048966910"
                                    },
                                    Height   = 512,
                                    Width    = 512,
                                    FileSize = 11356
                                },
                                StickerCollectionId         = 265723345,
                                StickerCollectionAccessHash = "-8925386374726878396",
                                StickerId = 1345218
                            }, LastUser);


                            //var welcomeSticker = SendMessageTools.GetStickerMessage(new SendSticker()
                            //{
                            //    Type = "Sticker",
                            //    FastPreview = null,
                            //    Image256 = new Model.Image()
                            //    {
                            //        FileLocation = new FileLocation()
                            //        {
                            //            FileStorageVersion = 1,
                            //            AccessHash = "1884281475",
                            //            FileId = "5894772107577788931"
                            //        },
                            //        Height = 256,
                            //        Width = 256,
                            //        FileSize = 4924
                            //    },
                            //    Image512 = new Model.Image()
                            //    {
                            //        FileLocation = new FileLocation()
                            //        {
                            //            FileStorageVersion = 1,
                            //            AccessHash = "1884281475",
                            //            FileId = "5894772107577788931"
                            //        },
                            //        Height = 512,
                            //        Width = 512,
                            //        FileSize = 11356
                            //    },
                            //    StickerCollectionId = 265723345,
                            //    StickerCollectionAccessHash = "-8925386374726878396",
                            //    StickerId = 1345218
                            //}, LastUser);

                            socketConnection.Send(welcomeSticker);
                        }
                    }
                    else
                    {
                        var msgType = baleObject["body"]["message"]["$type"].Value <string>();
                        if (msgType == "TemplateMessageResponse")
                        {
                            //این دستور از یک دکمه اومده
                            var textMessage = baleObject["body"]["message"]["textMessage"].Value <string>();
                            txtRec.Text += msgType + "\tBTN:" + textMessage + "\r\n";
                        }
                        else if (baleObject["body"]["message"]["mimeType"] != null)
                        {
                            //این پیام حاوی فایل یا سند یا عکس است
                            var mimeType = baleObject["body"]["message"]["mimeType"].Value <string>();
                            txtRec.Text += msgType + "\t" + mimeType + "\r\n";
                        }
                        else
                        {
                            txtRec.Text += msgType;
                        }
                    }
                }

                if (mainType == "Response")
                {
                    if (baleObject["body"]["url"] != null)
                    {
                        //دریافت پاسخ برای آپلود فایل و ارسال فایل
                        var id          = baleObject["id"].Value <long>();
                        var receivedUrl = baleObject["body"]["url"].Value <string>();

                        if (SendMessageTools.IsDownloadPending(id))
                        {
                            var fileName = SendMessageTools.GetDownloadFilename(id);
                            var dlUrl    = receivedUrl + "?filename=" + fileName;
                            socketConnection.Log.Info("Download File");
                            socketConnection.Log.Info(dlUrl);
                            SendMessageTools.DownloadFile(dlUrl, socketConnection, fileName);
                            SendMessageTools.DeleteDownload(id);
                        }
                        else if (SendMessageTools.IsUploadPending(id))
                        {
                            FileCache.FileInfoModel fileInfoModel;
                            if (SendMessageTools.UploadFile(id, receivedUrl, socketConnection, out fileInfoModel))
                            {
                                //send Info
                                var fileId = baleObject["body"]["fileId"].Value <string>();
                                var hash   = baleObject["body"]["userId"].Value <long>();

                                string msg = null;

                                //تشخیص ارسال عکس
                                if (fileInfoModel.UploadType == UploadTypeEnum.Document)
                                {
                                    msg = SendMessageTools.GetDocumentMessage(new SendDocument()
                                    {
                                        Type       = "Document",
                                        AccessHash = hash,
                                        Algorithm  = "algorithm",
                                        CheckSum   = "checkSum",
                                        Caption    = new Caption()
                                        {
                                            Text = txtPayam.Text, Type = "Text"
                                        },
                                        Ext                = null,
                                        FileId             = fileId,
                                        FileSize           = fileInfoModel.Size,
                                        FileStorageVersion = 1,
                                        MimeType           = "application/document",
                                        Name               = fileInfoModel.Name,
                                        Thumb              = null
                                    }, LastUser);
                                }
                                else if (fileInfoModel.UploadType == UploadTypeEnum.Photo)
                                {
                                    LastPhoto = new SendPhoto()
                                    {
                                        Type       = "Document",
                                        AccessHash = hash,
                                        Algorithm  = "algorithm",
                                        CheckSum   = "checkSum",
                                        Caption    = new Caption()
                                        {
                                            Text = txtPayam.Text, Type = "Text"
                                        },
                                        FileId             = fileId,
                                        FileSize           = fileInfoModel.Size,
                                        FileStorageVersion = 1,
                                        Name     = fileInfoModel.Name,
                                        MimeType = "image/jpeg",
                                        Ext      = new Ext()
                                        {
                                            Type   = "Photo",
                                            Width  = fileInfoModel.Width,
                                            Height = fileInfoModel.Height
                                        },
                                        Thumb = new Thumb()
                                        {
                                            ThumbThumb = "None",
                                            Width      = fileInfoModel.Width,
                                            Height     = fileInfoModel.Height
                                        }
                                    };
                                    msg = SendMessageTools.GetPhotoMessage(LastPhoto, LastUser);
                                }
                                else if (fileInfoModel.UploadType == UploadTypeEnum.Voice)
                                {
                                    msg = SendMessageTools.GetSendVoice(new SendVoice()
                                    {
                                        Type       = "Document",
                                        AccessHash = hash,
                                        Algorithm  = "algorithm",
                                        CheckSum   = "checkSum",
                                        Caption    = new Caption()
                                        {
                                            Text = txtPayam.Text, Type = "Text"
                                        },
                                        FileId             = fileId,
                                        FileSize           = fileInfoModel.Size,
                                        FileStorageVersion = 1,
                                        Name     = fileInfoModel.Name,
                                        MimeType = "audio/mp3",
                                        Ext      = new Ext()
                                        {
                                            Type     = "Voice",
                                            Duration = (int)(Convert.ToDouble(fileInfoModel.Duration) * 1000)
                                        }
                                    }, LastUser);
                                }

                                if (msg != null)
                                {
                                    socketConnection.Send(msg);
                                }

                                SendMessageTools.DeleteCacheUpload(id);
                            }
                        }
                    }
                }

                txtRec.SelectionStart = txtRec.TextLength;
                txtRec.ScrollToCaret();
            }
            else
            {
                ws.Log.Info("Binary Message");
                WriteLog(Convert.ToBase64String(e.RawData));
            }
        }
Ejemplo n.º 36
0
 public void Send(string content)
 {
     _socket?.Send(content);
 }
Ejemplo n.º 37
0
 private void websocket_Opened(object sender, EventArgs e)
 {
     _webSocket.Send("Join The Game");
 }
Ejemplo n.º 38
-1
	void Connect(){
		int id = (int)((1.0+Random.value)*0x10000);
		ws =  new WebSocket("ws://localhost:3000/websocket");
		
		// called when websocket messages come.
		ws.OnMessage += (sender, e) =>
		{
			//JSONObjectで解析
			JSONObject json = new JSONObject(e.Data);
			switch(json[0][0].str){
			case "new_message":
				messages.Add(string.Format("> {0}:{1}",json[0][1]["data"]["name"].str,
				                           json[0][1]["data"]["body"].str));
				if(messages.Count > 10){
					messages.RemoveAt(0);
				}
				break;
			case "websocket_rails.ping":
				Debug.Log(string.Format("Send: [\"websocket_rails.pong\",{{\"id\":{0},\"data\":{{}}}}]", id));
				ws.Send(string.Format("[\"websocket_rails.pong\",{{\"id\":{0},\"data\":{{}}}}]", id));
				this.message = "";
				break;
			}
			Debug.Log("Receive: " + e.Data);
		};
		
		ws.Connect();
		Debug.Log("Connect to: " + ws.Url);
	}
Ejemplo n.º 39
-1
        public async Task TestConnectWebSocket()
        {
            var wsUrl = Resources.WsServerAddress + "test";
            Assert.IsNotNull(WebServer.Module<WebSocketsModule>(), "WebServer has WebSocketsModule");

            Assert.AreEqual(WebServer.Module<WebSocketsModule>().Handlers.Count, 1, "WebSocketModule has one handler");

#if NET46
            var clientSocket = new ClientWebSocket();
            var ct = new CancellationTokenSource();
            await clientSocket.ConnectAsync(new Uri(wsUrl), ct.Token);

            Assert.AreEqual(WebSocketState.Open, clientSocket.State, "Connection is open");

            var message = new ArraySegment<byte>(System.Text.Encoding.Default.GetBytes("HOLA"));
            var buffer = new ArraySegment<byte>(new byte[1024]);

            await clientSocket.SendAsync(message, WebSocketMessageType.Text, true, ct.Token);
            var result = await clientSocket.ReceiveAsync(buffer, ct.Token);

            Assert.IsTrue(result.EndOfMessage, "End of message is true");
            Assert.IsTrue(System.Text.Encoding.UTF8.GetString(buffer.Array).TrimEnd((char) 0) == "WELCOME", "Final message is WELCOME");
#else
            var clientSocket = new WebSocket(wsUrl);
            clientSocket.Connect();            

            Assert.AreEqual(WebSocketState.Open, clientSocket.State, "Connection is open");

            clientSocket.Send("HOLA");
            await Task.Delay(100);
#endif
        }