/// <summary> /// Broadcast text from server to all connected clients /// </summary> /// <param name="text"></param> public void BroadcastText(string text) { CCriticalSection CCBroadcast = new CCriticalSection(); CCBroadcast.Enter(); try { if (ConnectedClientsIndexes.Count > 0) { byte[] b = Encoding.GetEncoding(28591).GetBytes(text); foreach (uint i in ConnectedClientsIndexes) { if (!SharedKeyRequired || (SharedKeyRequired && ClientReadyAfterKeyExchange.Contains(i))) { SocketErrorCodes error = SecureServer.SendDataAsync(i, b, b.Length, (x, y, z) => { }); if (error != SocketErrorCodes.SOCKET_OK && error != SocketErrorCodes.SOCKET_OPERATION_PENDING) { Debug.Console(2, error.ToString()); } } } } CCBroadcast.Leave(); } catch (Exception ex) { CCBroadcast.Leave(); Debug.Console(2, this, Debug.ErrorLogLevel.Error, "Error Broadcasting messages from server. Error: {0}", ex.Message); } }
public int Connect(String address, int target_port, int src_port, string myAddress) { Logger.Log("Connect({0},{1},{2},{3})", address, target_port, src_port, myAddress); if (client != null) { if (client.ServerStatus == SocketStatus.SOCKET_STATUS_CONNECTED) { DisconnectRequest(); client.DisableUDPServer(); client = null; } } SocketErrorCodes error = SocketErrorCodes.SOCKET_INVALID_STATE; try { this.myAddress = KnxHelper.GetAddress(myAddress); remoteEndpoint = get_IPEndpoint(address, target_port); if (src_port <= 0) { src_port = target_port; } localEndpoint = get_IPEndpoint(getLocalIP(), src_port); client = new UDPServer(remoteEndpoint, src_port, buffersz, EthernetAdapterType.EthernetLANAdapter); InitialParametersClass.ReadInInitialParameters(1); error = client.EnableUDPServer(); if (error == SocketErrorCodes.SOCKET_OK) { // start recieveing //error = client.ReceiveDataAsync(udpReceiver); //if (error == SocketErrorCodes.SOCKET_OPERATION_PENDING) //{ error = ConnectRequest(); if (error != SocketErrorCodes.SOCKET_OK) { client.DisableUDPServer(); client = null; } else { udpReadTimer.Reset(); stateRequestTimer.Reset(stateRequestTimerInterval); } } } catch (System.Exception e) { Logger.Log("Connect: Exception ({0})", e.Message); return(-1); } Logger.Log("Connect: ({0})", error); return(Convert.ToInt32(error)); }
object SendThreadProcess(object o) { #if DEBUG CrestronConsole.PrintLine("{0}.SendThreadProcess() Start", this.GetType().Name); #endif while (!_sendQueue.IsEmpty) { byte[] data = _sendQueue.Dequeue(); SocketErrorCodes err = SendPacket(_client, data); #if DEBUG CrestronConsole.PrintLine("{0} Send process result - {1}", this.GetType().Name, err); #endif if (err != SocketErrorCodes.SOCKET_OK) { ErrorLog.Error("{0}.Send process - Error sending data to socket, {1}", this.GetType().Name, err); } CrestronEnvironment.AllowOtherAppsToRun(); Thread.Sleep(0); } #if DEBUG CrestronConsole.PrintLine("{0}.SendThreadProcess() End", this.GetType().Name); #endif return(null); }
private static void SendDataAsync(string dataToSend) { try { byte[] SendData = System.Text.Encoding.ASCII.GetBytes(dataToSend); for (uint index = 1; index <= tcpServer.NumberOfClientsConnected; index++) { if (debug > 0) { CrestronConsole.Print("\n Catch Connect SendDataAsync attempt for index: " + index); } if (tcpServer.ClientConnected(index)) { SocketErrorCodes resultCodes = tcpServer.SendDataAsync(index, SendData, SendData.Length, OnTCPServerSendCallback); if (debug > 0) { CrestronConsole.Print("\n Catch Connect SendDataAsync resultCodes: " + resultCodes.ToString()); } } else { CrestronConsole.Print("\n Catch Connect SendDataAsync client not connected at index: " + index); } } } catch (Exception e) { ErrorLog.Error("error = " + e.Message); } }
private void Read(UDPServer myUDPServer, int numberOfBytesReceived) { if (myUDPServer == null) { ILiveDebug.Instance.WriteLine("UDPReadError"); return; } // ILiveDebug.Instance.WriteLine("UDPRec:"+ numberOfBytesReceived.ToString()+"|"+myUDPServer.ToString()+"|"+ this.NetDataReceived.ToString()); byte[] rbytes = new byte[numberOfBytesReceived]; if (numberOfBytesReceived > 0) { string messageReceived = Encoding.GetEncoding(28591).GetString(myUDPServer.IncomingDataBuffer, 0, numberOfBytesReceived); if (this.NetDataReceived != null) { NetDataReceived(this, messageReceived, null); } } try { SocketErrorCodes code = myUDPServer.ReceiveDataAsync(this.Read); Thread.Sleep(300); } catch (Exception) { } }
public void Listen() { while (true) { SocketErrorCodes codes = tcp.WaitForConnection(); // TcpClient client = tcpServer.AcceptTcpClient(); while (true) { try { // ILiveDebug.WriteLine("ReceiveData"); int i = tcp.ReceiveData(); if (i > 0) { string readdata = System.Text.Encoding.GetEncoding(28591).GetString(tcp.IncomingDataBuffer, 0, i); if (this.TcpDataEvent != null) { this.TcpDataEvent(readdata); } } else { Thread.Sleep(1000); } } catch (Exception e) { ILiveDebug.Instance.WriteLine("TCPError:" + e.Message); // break; } } } }
public object StartListen(object o) { Listener = new TCPServer("0.0.0.0", ServerPort, MaxBufferSize, EthernetAdapterType.EthernetLANAdapter, ConnectionsQueueLength); Listener.SocketStatusChange += new TCPServerSocketStatusChangeEventHandler(Listener_SocketStatusChange); //WebSocketAddress while (true) { //While Wait Connect try { SocketErrorCodes codes = Listener.WaitForConnection("0.0.0.0", this.OnClientConnect); } catch (Exception ex) { // logger.Log(ex.Message); } } // ConnectionSocket = new TCPServer("0.0.0.0", port, 4096); // ConnectionSocket.SocketStatusChange += new TCPServerSocketStatusChangeEventHandler(tcp_SocketStatusChange); // this.Open(); //ILiveTCPServer tcp = new ILiveTCPServer(8800); //tcp.TcpDataEvent += this.OnTcpReceived; //tcp.Listen(); return(null); }
/// <summary> /// 启动WebSocket服务 启动TCP连接,并监听客户端连接 连接数量20 /// </summary> public void StartServer() { Listener = new TCPServer("0.0.0.0", ServerPort, MaxBufferSize, EthernetAdapterType.EthernetLANAdapter, ConnectionsQueueLength); Listener.SocketStatusChange += new TCPServerSocketStatusChangeEventHandler(Listener_SocketStatusChange); //WebSocketAddress while (true) { //While Wait Connect try { SocketErrorCodes codes = Listener.WaitForConnection("0.0.0.0", this.OnClientConnect); } catch (Exception ex) { if (this.Log != null) { this.Log(ex.Message); } // logger.Log(ex.Message); } } }
public void Start() { try { OnServerStart(this, EventArgs.Empty); udpServer = new UDPServer(this.Endpoint, this.Port, this.BufferSize); SocketErrorCodes errorEnable = udpServer.EnableUDPServer(this.Endpoint.Address, this.Endpoint.Port); if (errorEnable == SocketErrorCodes.SOCKET_OK) { OnServerStarted(this, EventArgs.Empty); started = true; SocketErrorCodes errorRx = udpServer.ReceiveDataAsync(DataReceived); if (errorRx != SocketErrorCodes.SOCKET_OK) { throw new ApplicationException(SocketError.Text(errorRx)); } } else { throw new ApplicationException(SocketError.Text(errorEnable)); } } catch (Exception e) { ErrorLog.Error("UDPSocket start error {0}", e.Message); OnError(this, new OnErrorArgs(e)); } }
private void CheckForWaitingConnection() { SocketErrorCodes error = this.server.WaitForConnectionAsync(tcpServerClientConnectCallback); CrestronConsole.PrintLine("Server> WaitingForConnection[{0}] [{1}]", error, this.server.MaxNumberOfClientSupported); _waiting = (error == SocketErrorCodes.SOCKET_OPERATION_PENDING); }
// Methods public void WakeOnLAn() { try { errorCode = wakeOnLan.EnableUDPServer(IPAddress.Any, 0, 9); if (errorCode != SocketErrorCodes.SOCKET_OK) { ErrorCodes(errorCode); } wakeOnLan.EthernetAdapterToBindTo = EthernetAdapterType.EthernetLANAdapter; errorCode = wakeOnLan.SendData(wolPacket, wolPacket.Length, ipAddress, portNumber, false); CrestronConsole.PrintLine("Ip Address is: {0} and Port is {1} and packet length is: {2}", ipAddress, portNumber, wolPacket.Length); if (errorCode != SocketErrorCodes.SOCKET_OK) { ErrorCodes(errorCode); } string message = BitConverter.ToString(wolPacket); CrestronConsole.PrintLine(message); wakeOnLan.DisableUDPServer(); } catch (Exception e) { CrestronConsole.PrintLine("WakeOn LAn Send packet Error is: " + e); } }
private void Read(UDPServer myUDPServer, int numberOfBytesReceived) { byte[] rbytes = new byte[numberOfBytesReceived]; if (numberOfBytesReceived > 0) { string messageReceived = Encoding.GetEncoding(28591).GetString(myUDPServer.IncomingDataBuffer, 0, numberOfBytesReceived); NetDataReceived(this, new NetPortSerialDataEventArgs() { SerialData = messageReceived, SerialEncoding = eStringEncoding.eEncodingASCII }); // OnDataReceived(messageReceived); // CrestronConsole.PrintLine("messageReceived:" + messageReceived); } try { // CrestronConsole.PrintLine("Recv:" + ILiveUtil.ToHexString(rbytes)); SocketErrorCodes code = myUDPServer.ReceiveDataAsync(this.Read); Thread.Sleep(300); } catch (Exception) { } }
public void OnClientConnect(TCPServer myTCPServer, uint clientIndex) { if (myTCPServer.ClientConnected(clientIndex)) { SocketConnection socketConn = new SocketConnection(); socketConn.clientindex = clientIndex; socketConn.ConnectionSocket = myTCPServer; socketConn.NewConnection += new NewConnectionEventHandler(socketConn_NewConnection); socketConn.DataReceived += new DataReceivedEventHandler(socketConn_BroadcastMessage); socketConn.Disconnected += new DisconnectedEventHandler(socketConn_Disconnected); socketConn.Log += this.Log; myTCPServer.ReceiveDataAsync(clientIndex, socketConn.ManageHandshake, 0); connectionSocketList.Add(socketConn); } try { SocketErrorCodes codes = Listener.WaitForConnectionAsync(this.OnClientConnect); } catch (Exception ex) { if (this.Log != null) { this.Log(ex.Message); } // logger.Log(ex.Message); } this.Log(string.Format("Client Index {0} Connected", clientIndex)); }
private void Conn() { if (this.tcp != null) { //连接到服务器 SocketErrorCodes codes = tcp.ConnectToServerAsync(this.TCPClientConnectCallback); } }
/// <summary> /// SIMPL+ can only execute the default constructor. If you have variables that require initialization, please /// use an Initialize method /// </summary> public void listen(int port) { clients = new ArrayList(); this.server = new TCPServer("0.0.0.0", port, bufferSize, EthernetAdapterType.EthernetLANAdapter, maxClient); SocketErrorCodes error = server.WaitForConnectionAsync(onConnect); server.SocketStatusChange += onStatuChange; }
/// <summary> /// send data to server /// </summary> /// <param name="tx">data</param> public void DataTransmit(SimplSharpString tx) { var err = new SocketErrorCodes(); byte[] bytes = Encoding.UTF8.GetBytes(tx.ToString()); err = _tcpClient.SendData(bytes, bytes.Length); Debug("Data transmitted: " + tx.ToString(), ErrorLevel.None, err.ToString()); }
public void DisconnectFromServer() { SocketErrorCodes returnCodes = tcpClient.DisconnectFromServer(); if (debug > 0) { CrestronConsole.PrintLine("TCPClientClass DisconnectFromServer returnCodes: " + returnCodes); } }
public void SendData(SimplSharpString dataToSend) { byte[] pBufferToSend = System.Text.Encoding.ASCII.GetBytes(dataToSend.ToString()); SocketErrorCodes returnCode = tcpClient.SendData(pBufferToSend, pBufferToSend.Length); if (debug > 0) { CrestronConsole.PrintLine("\n TCPClientClass SendData returnCode: " + returnCode.ToString()); } }
/// <summary> /// Start listening on the specified port /// </summary> public void Listen() { ServerCCSection.Enter(); try { if (Port < 1 || Port > 65535) { Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Server '{0}': Invalid port", Key); ErrorLog.Warn(string.Format("Server '{0}': Invalid port", Key)); return; } if (string.IsNullOrEmpty(SharedKey) && SharedKeyRequired) { Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Server '{0}': No Shared Key set", Key); ErrorLog.Warn(string.Format("Server '{0}': No Shared Key set", Key)); return; } if (SecureServer == null) { SecureServer = new SecureTCPServer(Port, MaxClients); if (HeartbeatRequired) { SecureServer.SocketSendOrReceiveTimeOutInMs = (this.HeartbeatRequiredIntervalMs * 5); } SecureServer.HandshakeTimeout = 30; SecureServer.SocketStatusChange += new SecureTCPServerSocketStatusChangeEventHandler(SecureServer_SocketStatusChange); } else { SecureServer.PortNumber = Port; } ServerStopped = false; // Start the listner SocketErrorCodes status = SecureServer.WaitForConnectionAsync(IPAddress.Any, SecureConnectCallback); if (status != SocketErrorCodes.SOCKET_OPERATION_PENDING) { Debug.Console(0, this, Debug.ErrorLogLevel.Error, "Error starting WaitForConnectionAsync {0}", status); } else { ServerStopped = false; } OnServerStateChange(SecureServer.State); Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Secure Server Status: {0}, Socket Status: {1}", SecureServer.State, SecureServer.ServerSocketStatus); ServerCCSection.Leave(); } catch (Exception ex) { ServerCCSection.Leave(); ErrorLog.Error("{1} Error with Dynamic Server: {0}", ex.ToString(), Key); } }
public ILiveTPC5(int port) { try { server.EnableUDPServer("192.168.188.25", 6004, port); SocketErrorCodes code = server.ReceiveDataAsync(this.Read); } catch (Exception) { } }
public override int Send(byte[] buffer, int offset, int size, SocketFlags socketFlags) { var client = _client; Debug.WriteLine(String.Format("Client ({2}): Send [offset = {1}, size = {0}]", size, offset, InternalRemoteEndPoint)); CheckDisposed(); if (_shutdown.HasValue && (_shutdown == SocketShutdown.Send || _shutdown == SocketShutdown.Both)) { throw new SocketException(SocketError.Shutdown); } if (client.ClientStatus != SocketStatus.SOCKET_STATUS_CONNECTED) { throw new SocketException(SocketError.NotConnected); } if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException("offset"); } if (size < 0 || size > buffer.Length - offset) { throw new ArgumentOutOfRangeException("size"); } if (size == 0) { return(0); } client.SocketSendOrReceiveTimeOutInMs = SendTimeout; SocketErrorCodes result = client.SendData(buffer, offset, size); client.SocketSendOrReceiveTimeOutInMs = 0; if (result != SocketErrorCodes.SOCKET_OK) { throw new SocketException(result.ToError()); } UpdateSentData(size); return(size); }
public void Initialize(int port) { if (port <= 0) { return; } this.server = new TCPServer("0.0.0.0", port, 1024, EthernetAdapterType.EthernetUnknownAdapter, 100); this.server.SocketStatusChange += new TCPServerSocketStatusChangeEventHandler(_server_SocketStatusChange); SocketErrorCodes error = this.server.WaitForConnectionAsync(tcpServerClientConnectCallback); _waiting = (error == SocketErrorCodes.SOCKET_OPERATION_PENDING); }
public void Connect() { try { server.EnableUDPServer(this.host, this.localport, this.remoteport); SocketErrorCodes code = server.ReceiveDataAsync(this.Read); } catch (Exception) { } }
public static string Text(SocketErrorCodes e) { switch (e) { case SocketErrorCodes.SOCKET_OK: return(String.Format("Error [{0}] Success", e)); case SocketErrorCodes.SOCKET_INVALID_STATE: return(String.Format("Error [{0}] Client, udpServer or UDP not in initial state", e)); case SocketErrorCodes.SOCKET_NO_HOSTNAME_RESOLVE: return(String.Format("Error [{0}] Could not resolve specified hostname", e)); case SocketErrorCodes.SOCKET_INVALID_PORT_NUMBER: return(String.Format("Error [{0}] Port not in range of 0-65535", e)); case SocketErrorCodes.SOCKET_NOT_CONNECTED: return(String.Format("Error [{0}] Unable to establish a connection", e)); case SocketErrorCodes.SOCKET_BUFFER_NOT_ALLOCATED: return(String.Format("Error [{0}] Unable to allocate socket buffer", e)); case SocketErrorCodes.SOCKET_ADDRESS_NOT_SPECIFIED: return(String.Format("Error [{0}] Address not specified", e)); case SocketErrorCodes.SOCKET_OUT_OF_MEMORY: return(String.Format("Error [{0}] Out of memory", e)); case SocketErrorCodes.SOCKET_CONNECTION_IN_PROGRESS: return(String.Format("Error [{0}] Socket connection in progress", e)); case SocketErrorCodes.SOCKET_NOT_ALLOWED_IN_SECURE_MODE: return(String.Format("Error [{0}] Sockets are not allowed in the secure mode", e)); case SocketErrorCodes.SOCKET_SPECIFIED_PORT_ALREADY_IN_USE: return(String.Format("Error [{0}] Specified port is already in use", e)); case SocketErrorCodes.SOCKET_INVALID_CLIENT_INDEX: return(String.Format("Error [{0}] Client (socket) index is invalid", e)); case SocketErrorCodes.SOCKET_MAX_CONNECTIONS_REACHED: return(String.Format("Error [{0}] Client connections reached the MAX", e)); case SocketErrorCodes.SOCKET_INVALID_ADDRESS_ADAPTER_BINDING: return(String.Format("Error [{0}] Address specified and the EthernetAdapterToBindTo do not match", e)); case SocketErrorCodes.SOCKET_OPERATION_PENDING: return(String.Format("Error [{0}] Socket operation is pending", e)); default: return(String.Format("Error [{0}] Unexpected error code", e)); } }
/// <summary> /// InitializeSystem - this method gets called after the constructor /// has finished. /// /// Use InitializeSystem to: /// * Start threads /// * Configure ports, such as serial and verisports /// * Start and initialize socket connections /// Send initial device configurations /// /// Please be aware that InitializeSystem needs to exit quickly also; /// if it doesn't exit in time, the SIMPL#Pro program will exit. /// </summary> public override void InitializeSystem() { try { server = new TCPServer("0.0.0.0", 9876, 4000, EthernetAdapterType.EthernetUnknownAdapter, 1000); SocketErrorCodes err = server.WaitForConnectionAsync(ServerConnectedCallback); CrestronConsole.PrintLine("WaitForConnectionAsync returned: " + err); } catch (Exception e) { ErrorLog.Error("Error in InitializeSystem: {0}", e.Message); } }
// public event Push16IHandler Push16IEvent; public ILiveInfocus(string ip, int port) { try { server.EnableUDPServer(ip, 6004, port); SocketErrorCodes code = server.ReceiveDataAsync(this.Read); } catch (Exception) { // CrestronConsole.PrintLine(ex.Message); // ILiveDebug.Instance.WriteLine(ex.Message); } }
public ILiveGRODIGY16I(int port) { try { server.EnableUDPServer("192.168.188.25", 6005, port); SocketErrorCodes code = server.ReceiveDataAsync(this.Read); } catch (Exception ex) { CrestronConsole.PrintLine(ex.Message); // ILiveDebug.Instance.WriteLine(ex.Message); } }
public virtual SocketErrorCodes Send(byte[] bytes) { if (this.Socket.ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED) { SocketErrorCodes err = Socket.SendData(bytes, bytes.Length); if (err != SocketErrorCodes.SOCKET_OK) { ErrorLog.Error("{0} Send to {1} Error: {2}", this.GetType().ToString(), Socket.AddressClientConnectedTo, err.ToString()); } return(err); } return(SocketErrorCodes.SOCKET_NOT_CONNECTED); }
private void CheckForWaitingConnection() { if (_numberOfClientsConnected < _server.MaxNumberOfClientSupported) { SocketErrorCodes error = _server.WaitForConnectionAsync("0.0.0.0", Server_ClientConnectCallback); CrestronConsole.PrintLine("Server> WaitingForConnection[{0}] [{1}]", error, _server.MaxNumberOfClientSupported); _waiting = (error == SocketErrorCodes.SOCKET_OPERATION_PENDING); } else { CrestronConsole.PrintLine("Server> No more connections available."); _waiting = false; } }
public void ConnectToServer() { SocketErrorCodes returnCode = tcpClient.ConnectToServer(); if (debug > 0) { CrestronConsole.PrintLine("\n TCPClientClass ConnectToServer returnCode: " + returnCode.ToString()); } if (returnCode == 0) { tcpClient.ReceiveDataAsync(OnDataReceiveEventCallback); } }