public SocketStream(SocketInfo info, IOLoop ioloop) : base(ioloop) { state = SocketState.Open; port = info.port; address = info.Address; }
// -- public Client(IClientListener listener) { this.listeners = new List<IClientListener>(); this.listeners.Add(listener); this.username = User.Instance.username; this.id = User.Instance.id; this.state = SocketState.DISCONNECTED; }
public SocketStream(Socket socket, IOLoop ioloop) : base(ioloop) { this.socket = socket; if (socket != null) { socket.Blocking = false; SetHandle (IOWatcher.GetHandle (socket)); state = SocketState.Open; } }
public SocketStream(SocketInfo info, IOLoop ioloop) : base(ioloop) { fd = info.fd; if (fd > 0) { SetHandle (fd); state = SocketState.Open; } port = info.port; }
public void CloseAbortively() { try { ClientSocket.AbortiveClose(); ClientSocket = null; ClientSocketState = SocketState.Closed; Console.WriteLine("Abortively closed socket"); } catch (Exception ex) { ResetSocket(); Console.WriteLine("Error aborting socket: [" + ex.GetType().Name + "] " + ex.Message); } finally { RefreshDisplay(); } }
/// <summary> /// Connexion au serveur /// </summary> /// <param name="host">Localisation du serveur</param> /// <param name="port">Id of friend</param> /// <param name="authenticate">Authentification automatique</param> public void Connect(string host = HOST, int port = PORT, bool authenticate = true) { this._sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { _sock.Connect(host, port); this.state = SocketState.CONNECTED; run = new Thread(new ThreadStart(ReceiveLoop)); run.Name = "ReceiveThread"; run.IsBackground = true; run.Start(); if (authenticate) this.Authenticate(); } catch (Exception e) { Debug.Log("Erreur de connexion : " + e.Message); } }
private void AcceptCallback(IAsyncResult ar) { _reset.Set(); Socket listener = (Socket)ar.AsyncState; Socket handler = listener.EndAccept(ar); SocketState state = new SocketState() { Socket = handler }; WaitForData(state); }
private void SendRemainingBytes(int offset, int count) { lock (this) { if (socketState == SocketState.Idle) { socketState = SocketState.Sending; this.eventArgs.SetBuffer(offset, count); bool asynchronous = this.socket.SendAsync(this.eventArgs); if (!asynchronous) { this.IOCompleted(this, this.eventArgs); } } else { Console.WriteLine("Error: we shouldn't have come here 2"); } } }
/// <summary> /// Starts the passive mode listener. /// </summary> private void PassiveModeStartListening() { var inPassiveModeStartListening = false; lock (_SyncLock) { inPassiveModeStartListening = _InPassiveModeStartListening; if (!inPassiveModeStartListening) { _InPassiveModeStartListening = true; } } if (!inPassiveModeStartListening) { ConnectionStatus = ConnectionStatus.Connecting; var access = Access; _AccessFilter = access == null ? null : Factory.Singleton.Resolve <IAccessFilter>(); if (_AccessFilter != null) { _AccessFilter.Initialise(access); } Socket socket = null; try { while (socket == null && !_Closed) { try { socket = CreatePassiveModeListeningSocket(); ConnectionStatus = ConnectionStatus.Waiting; RecordMiscellaneousActivity("Listening for incoming connections on port {0}", Port); while (!_Closed) { using (var state = new SocketState(socket)) { socket.BeginAccept(PassiveModeAccept, state); while (!state.WaitHandle.WaitOne(250)) { if (_Closed) { break; } } } } } catch (Exception ex) { OnExceptionCaught(new EventArgs <Exception>(ex)); } if (socket == null && !_Closed) { PauseWhileTestingClosed(RetryConnectTimeout); } } } finally { AbandonAllConnections(); if (socket != null) { try { socket.Close(); ((IDisposable)socket).Dispose(); } catch { ; } } _InPassiveModeStartListening = false; ConnectionStatus = ConnectionStatus.Disconnected; } } }
///////////////////////////////////////////////////////////////////////////////////////// // Client-Side Code ///////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Begins the asynchronous process of connecting to a server via BeginConnect, /// and using ConnectedCallback as the method to finalize the connection once it's made. /// /// If anything goes wrong during the connection process, toCall should be invoked /// with a new SocketState with its ErrorOccured flag set to true and an appropriate message /// placed in its ErrorMessage field. Between this method and ConnectedCallback, toCall should /// only be invoked once on error. /// /// This connection process should timeout and produce an error (as discussed above) /// if a connection can't be established within 3 seconds of starting BeginConnect. /// /// </summary> /// <param name="toCall">The action to take once the connection is open or an error occurs</param> /// <param name="hostName">The server to connect to</param> /// <param name="port">The port on which the server is listening</param> public static void ConnectToServer(Action <SocketState> toCall, string hostName, int port) { // Establish the remote endpoint for the socket. IPHostEntry ipHostInfo; IPAddress ipAddress = IPAddress.None; // Determine if the server address is a URL or an IP try { ipHostInfo = Dns.GetHostEntry(hostName); bool foundIPV4 = false; foreach (IPAddress addr in ipHostInfo.AddressList) { if (addr.AddressFamily != AddressFamily.InterNetworkV6) { foundIPV4 = true; ipAddress = addr; break; } } // Didn't find any IPV4 addresses if (!foundIPV4) { SocketState errorSocketState = new SocketState(toCall, null); errorSocketState.ErrorOccured = true; errorSocketState.ErrorMessage = "Couldn't find any IPV4 addresses"; errorSocketState.OnNetworkAction(errorSocketState); return; } } catch (Exception) { // See if host name is a valid ipaddress try { ipAddress = IPAddress.Parse(hostName); } catch (Exception) { SocketState errorSocketState = new SocketState(toCall, null); errorSocketState.ErrorOccured = true; errorSocketState.ErrorMessage = "Host name isn't a valid ipaddress"; errorSocketState.OnNetworkAction(errorSocketState); } } // Create a TCP/IP socket. Socket socket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); // This disables Nagle's algorithm (google if curious!) // Nagle's algorithm can cause problems for a latency-sensitive // game like ours will be socket.NoDelay = true; try { SocketState TheServer = new SocketState(toCall, socket); IAsyncResult result = TheServer.TheSocket.BeginConnect(ipAddress, port, ConnectedCallback, TheServer); bool success = result.AsyncWaitHandle.WaitOne(3000, true); if (!TheServer.TheSocket.Connected) { TheServer.TheSocket.Close(); } } catch { SocketState errorSocketState = new SocketState(toCall, null); errorSocketState.ErrorOccured = true; errorSocketState.ErrorMessage = "An error occured while connecting to server"; errorSocketState.OnNetworkAction(errorSocketState); } }
/// <summary> /// 인자로 전달된 상태가 추가되었는지 확인합니다. /// </summary> /// <param name="state">검사할 상태.</param> /// <returns>True : 이미 추가됨 False : 추가되지 않음</returns> private bool ContaintsState(SocketState state) { return((_state & (int)state) == (int)state); }
private void SendAutomatchRooms(SocketState state, string validate, ChannelInfo[] rooms) { var bytes = new List <byte>(); // was ip IPEndPoint remoteEndPoint = ((IPEndPoint)state.Socket.RemoteEndPoint); bytes.AddRange(remoteEndPoint.Address.GetAddressBytes()); byte[] value2 = BitConverter.GetBytes((ushort)6500); bytes.AddRange(BitConverter.IsLittleEndian ? value2.Reverse() : value2); bytes.Add(3); // fields count bytes.Add(0); bytes.AddRange(DataFunctions.StringToBytes("hostname")); bytes.Add(0); bytes.Add(0); bytes.AddRange(DataFunctions.StringToBytes("numwaiting")); bytes.Add(0); bytes.Add(0); bytes.AddRange(DataFunctions.StringToBytes("maxwaiting")); bytes.Add(0); bytes.Add(0); // #GSP!<gamename>!X<encoded public IP><encoded public port><encoded private IP><encoded private port>X // JOIN #GSP!whammer40kdc!MJD13lhaPM // X<encoded public IP>X|<profile ID> foreach (var room in rooms) { var encodedEndPoint = room.Name.Split('!')[2]; //var localip0 = server.Get<string>("localip0"); //var localip1 = server.Get<string>("localip1"); //var localport = ushort.Parse(server.Get<string>("localport") ?? "0"); var queryPort = (ushort)6112; //(ushort)server.Get<int>("QueryPort"); var iPAddress = "192.168.1.31"; //server.Get<string>("localip4") ?? server.Get<string>("IPAddress"); bytes.Add(81); bytes.AddRange(IPAddress.Parse(iPAddress).GetAddressBytes()); bytes.AddRange(BitConverter.IsLittleEndian ? BitConverter.GetBytes(queryPort).Reverse() : BitConverter.GetBytes(queryPort)); bytes.Add(255); bytes.AddRange(DataFunctions.StringToBytes(room.Name)); bytes.Add(0); bytes.Add(255); bytes.AddRange(DataFunctions.StringToBytes(room.Users.Count().ToString())); bytes.Add(0); bytes.Add(255); bytes.AddRange(DataFunctions.StringToBytes("2")); bytes.Add(0); } bytes.AddRange(new byte[] { 0, 255, 255, 255, 255 }); var array = bytes.ToArray(); byte[] enc = GSEncoding.Encode(ChatServer.Gamekey, DataFunctions.StringToBytes(validate), array, array.LongLength); SendToClient(state, enc); }
/// <summary> /// Close the socket. This is NOT async. .Net doesn't have /// async closes. But, it can be *called* async, particularly /// from GotData. Attempts to do a shutdown() first. /// </summary> public override void Close() { Debug.WriteLine("Close"); lock (this) { /* switch (State) { case State.Closed: throw new InvalidOperationException("Socket already closed"); case State.Closing: throw new InvalidOperationException("Socket already closing"); } */ SocketState oldState = State; if (m_sock.Connected) { State = SocketState.Closing; } if (m_stream != null) m_stream.Close(); else { try { m_sock.Close(); } catch { } } if (oldState <= SocketState.Connected) m_listener.OnClose(this); if (m_watcher != null) m_watcher.CleanupSocket(this); State = SocketState.Closed; } }
/// <summary> /// Prepare to start accepting inbound requests. Call /// RequestAccept() to start the async process. /// </summary> /// <param name="addr">Address to listen on</param> /// <param name="backlog">The Maximum length of the queue of /// pending connections</param> public override void Accept(Address addr, int backlog) { lock (this) { m_addr = addr; m_sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Always reuse address. m_sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1); m_sock.Bind(m_addr.Endpoint); m_sock.Listen(backlog); State = SocketState.Listening; if (m_watcher != null) m_watcher.RegisterSocket(this); } }
/// <summary> /// Address resolution finished. Try connecting. /// </summary> /// <param name="addr"></param> private void OnConnectResolved(Address addr) { // Debug.WriteLine("connectresolved: " + addr.ToString()); lock (this) { if (State != SocketState.Resolving) { // closed in the mean time. Probably not an error. return; } if ((addr == null) || (addr.IP == null) || (addr.Endpoint == null)) { FireError(new AsyncSocketConnectionException("Bad host: " + addr.Hostname)); return; } if (m_watcher != null) m_watcher.RegisterSocket(this); m_addr = addr; State = SocketState.Connecting; if (Socket.OSSupportsIPv6 && (m_addr.Endpoint.AddressFamily == AddressFamily.InterNetworkV6)) { // Debug.WriteLine("ipv6"); m_sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp); } else { // Debug.WriteLine("ipv4"); m_sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); } // well, of course this isn't right. m_sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, 4 * m_buf.Length); } if (m_synch) { try { m_sock.Connect(m_addr.Endpoint); } catch (SocketException ex) { FireError(ex); return; } if (m_sock.Connected) { // TODO: check to see if this Mono bug is still valid #if __MonoCS__ m_sock.Blocking = true; m_stream = new NetworkStream(m_sock); m_sock.Blocking = false; #else m_stream = new NetworkStream(m_sock); #endif if (m_secureProtocol != SslProtocols.None) StartTLS(); lock (this) { State = SocketState.Connected; } m_listener.OnConnect(this); } else { AsyncClose(); FireError(new AsyncSocketConnectionException("could not connect")); } } else { #if __MonoCS__ m_sock.Blocking = false; #endif m_sock.BeginConnect(m_addr.Endpoint, new AsyncCallback(ExecuteConnect), null); } }
private void OnError(SocketState state, Exception e = null) { }
private void OnDataReceived(IAsyncResult async) { SocketState state = (SocketState)async.AsyncState; if (state == null || state.Socket == null || !state.Socket.Connected) { return; } try { // receive data from the socket int received = state.Socket.EndReceive(async); if (received == 0) { // when EndReceive returns 0, it means the socket on the other end has been shut down. return; } var receivedString = Encoding.ASCII.GetString(state.Buffer, 0, received); Logger.Info($"Data received: {receivedString}"); ParseRequest(state, receivedString); } catch (ObjectDisposedException) { if (state != null) { state.Dispose(); } state = null; return; } catch (SocketException e) { switch (e.SocketErrorCode) { case SocketError.ConnectionReset: if (state != null) { state.Dispose(); } state = null; return; case SocketError.Disconnecting: if (state != null) { state.Dispose(); } state = null; return; default: Logger.Error(e, $"Error receiving data. SocketErrorCode: {e.SocketErrorCode}"); if (state != null) { state.Dispose(); } state = null; return; } } catch (Exception e) { Logger.Error(e, $"Error receiving data"); } // and we wait for more data... WaitForData(state); }
/// <summary> /// Outbound connection. Eventually calls Listener.OnConnect() when /// the connection comes up. Don't forget to call RequestRead() in /// OnConnect()! /// </summary> /// <param name="addr"></param> public override void Connect(Address addr) { // Debug.WriteLine("starting connect to " + addr.ToString()); State = SocketState.Resolving; if (m_synch) { addr.Resolve(); OnConnectResolved(addr); } else { addr.Resolve(new AddressResolved(OnConnectResolved)); } }
private static byte[] PackServerList(SocketState state, IEnumerable <GameServer> servers, string[] fields, bool isAutomatch) { IPEndPoint remoteEndPoint = ((IPEndPoint)state.Socket.RemoteEndPoint); List <byte> data = new List <byte>(); data.AddRange(remoteEndPoint.Address.GetAddressBytes()); byte[] value2 = BitConverter.GetBytes((ushort)remoteEndPoint.Port); data.AddRange(BitConverter.IsLittleEndian ? value2.Reverse() : value2); if (fields.Length == 1 && fields[0] == "\u0004") { fields = new string[0]; } data.Add((byte)fields.Length); data.Add(0); foreach (var field in fields) { data.AddRange(Encoding.UTF8.GetBytes(field)); data.AddRange(new byte[] { 0, 0 }); } foreach (var server in servers) { // commented this stuff out since it caused some issues on testing, might come back to it later and see what's happening... // NAT traversal stuff... // 126 (\x7E) = public ip / public port / private ip / private port / icmp ip // 115 (\x73) = public ip / public port / private ip / private port // 85 (\x55) = public ip / public port // 81 (\x51) = public ip / public port /*var localip1 = server.Get<string>("localip1"); * var localip0 = server.Get<string>("localip0"); * var localport = ushort.Parse(server.Get<string>("localport") ?? "0"); * var queryPort = (ushort)server.Get<int>("QueryPort"); * var iPAddress = server.Get<string>("IPAddress"); * var publicIp = server.Get<string>("publicip"); * var bytes = Encoding.UTF8.GetBytes(publicIp);*/ // 1388419870 1294854161 var iPAddress = server.Get <string>("IPAddress"); var localport = ushort.Parse(server.Get <string>("localport") ?? "0"); var queryPort = (ushort)server.Get <int>("QueryPort"); var privateIp = server.Get <string>("localip0"); /* if (!String.IsNullOrWhiteSpace(localip0) && !String.IsNullOrWhiteSpace(localip1) && localport > 0) * { * data.Add(126); * data.AddRange(IPAddress.Parse(iPAddress).GetAddressBytes()); * data.AddRange(BitConverter.IsLittleEndian ? BitConverter.GetBytes((ushort)queryPort).Reverse() : BitConverter.GetBytes((ushort)queryPort)); * data.AddRange(IPAddress.Parse(localip0).GetAddressBytes()); * data.AddRange(BitConverter.IsLittleEndian ? BitConverter.GetBytes((ushort)localport).Reverse() : BitConverter.GetBytes((ushort)localport)); * data.AddRange(IPAddress.Parse(localip1).GetAddressBytes()); * * * } * else*/ // if (!String.IsNullOrWhiteSpace(privateIp) && localport > 0) // { var bytesIp = IPAddress.Parse(iPAddress).GetAddressBytes(); var portBytes = BitConverter.IsLittleEndian ? BitConverter.GetBytes(queryPort).Reverse().ToArray() : BitConverter.GetBytes(queryPort); var bytesLocalIp0 = IPAddress.Parse(privateIp).GetAddressBytes(); var localPortBytes = BitConverter.IsLittleEndian ? BitConverter.GetBytes(localport).Reverse().ToArray() : BitConverter.GetBytes(localport); data.Add(115); data.AddRange(bytesIp); data.AddRange(portBytes); data.AddRange(bytesLocalIp0); data.AddRange(localPortBytes); /* } * else * { * data.Add(81); // it could be 85 as well, unsure of the difference, but 81 seems more common... * data.AddRange(IPAddress.Parse(localIp).GetAddressBytes()); * data.AddRange(BitConverter.IsLittleEndian ? BitConverter.GetBytes(queryPort).Reverse() : BitConverter.GetBytes(queryPort)); * }*/ data.Add(255); for (int i = 0; i < fields.Length; i++) { var name = fields[i]; var f = GetField(server, name); data.AddRange(Encoding.UTF8.GetBytes(f)); if (i < fields.Length - 1) { data.Add(0); data.Add(255); } } data.Add(0); } data.Add(0); data.Add(255); data.Add(255); data.Add(255); data.Add(255); return(data.ToArray()); }
/// <summary> /// Error occurred in the class. Send to Listener. /// </summary> /// <param name="e"></param> protected void FireError(Exception e) { lock (this) { State = SocketState.Error; } if (e is SocketException) { Debug.WriteLine("Sock errno: " + ((SocketException) e).ErrorCode); } if (m_watcher != null) m_watcher.CleanupSocket(this); m_listener.OnError(this, e); }
protected void OnChangeState(SocketState newState) { SocketState prev = this.state; this.state = newState; if (this.StateChanged != null) this.StateChanged(new NetSockStateChangedEventArgs(this.state, prev)); if (this.state == SocketState.Connected) this.connectionTimer.Change(0, this.ConnectionCheckInterval); else if (this.state == SocketState.Closed) this.connectionTimer.Change(Timeout.Infinite, Timeout.Infinite); }
/// <summary> /// Initial set /// </summary> /// <param name="LastState">The last socket state</param> /// <param name="CurrentState">The current socket state</param> /// <param name="ErrorType">The error type of socket if state is "Errors"</param> public StateChangedEventArgs(SocketState LastState, SocketState CurrentState, SocketError ErrorType) { this.enum_LastState = LastState; this.enum_CurrentState = CurrentState; this.enum_ErrorType = ErrorType; }
private void beginAcceptCallback_forStartListening(IAsyncResult result) { Console.WriteLine("TransportLayerCommunicator::beginAcceptCallback_forStartListening ENTER"); SocketUtility.SocketListener.SocketListenState socketListenState = (SocketUtility.SocketListener.SocketListenState) result.AsyncState; // Signal the listener thread to continue. socketListenState.allDone.Set(); Socket listener = socketListenState.sock; Socket handler = listener.EndAccept(result); TransportLayerCommunicator transportLayerCommunicator = (TransportLayerCommunicator)(socketListenState.obj); SockMsgQueue sockMsgQueue = new SockMsgQueue(handler, transportLayerCommunicator ); IPAddress IP = ((IPEndPoint)(handler.RemoteEndPoint)).Address; SocketState socketState = new SocketState(); socketState.transportLayerCommunicator = transportLayerCommunicator; try { transportLayerCommunicator.commRegistry.Add(IP, sockMsgQueue); socketState.sock = handler; handler.BeginReceive( socketState.buffer, 0, socketState.buffer.Length, new SocketFlags(), new AsyncCallback(beginReceiveCallBack), socketState); Console.WriteLine("TransportLayerCommunicator::beginAcceptCallback_forStartListening EXIT"); } catch(System.ArgumentException) { socketState.sock = handler; handler.BeginReceive( socketState.buffer, 0, socketState.buffer.Length, new SocketFlags(), new AsyncCallback(beginReceiveCallBack), socketState); Console.WriteLine("TransportLayerCommunicator::beginAcceptCallback_forStartListening EXIT"); } Console.WriteLine("TransportLayerCommunicator::beginAcceptCallback_forStartListening EXIT"); }
/// <summary> /// Change socket state and raise socket state changed event /// </summary> /// <param name="NewState">The new socket state</param> /// <param name="ErrorType">The error type of socket if state is "Errors"</param> /// <param name="RaiseEventType">The raise event type</param> protected void ChangeSocketState(SocketState NewState, SocketError ErrorType, SocketStateRaiseEventType RaiseEventType) { SocketState LastState = this.State; this.enum_State = NewState; //类内唯一设置状态的语句 //要在Me.enum_State = NewState之后 if (NewState == SocketState.Closed) { ResetSocket(); } if (RaiseEventType == SocketStateRaiseEventType.Always || (RaiseEventType == SocketStateRaiseEventType.IfChanged && NewState != LastState)) { OnStateChanged(new StateChangedEventArgs(LastState, NewState, ErrorType)); } }
private void TrySend() { lock (this) { if (socketState == SocketState.Idle) { var messageToSend = outgoingMessages.Dequeue(); socketState = SocketState.Sending; this.eventArgs.SetBuffer(messageToSend, 0, messageToSend.Length); bool asynchronous = this.socket.SendAsync(this.eventArgs); if (!asynchronous) { this.IOCompleted(this, this.eventArgs); } } } }
void tcpClient_OnSocketState(object sender, SocketState state) { string stateText = (state == SocketState.Connected ? "成功":"失败"); statusLabel1.Text = string.Format("连接服务器[ {0}:{1}] {2}!", ServerIP, ServerPort, stateText); }
public void SetupTestConnections(bool clientSide, out TcpListener listener, out SocketState local, out SocketState remote, int port) { if (clientSide) { NetworkTestHelper.SetupSingleConnectionTest( out listener, out local, // local becomes client out remote, // remote becomes server port); } else { NetworkTestHelper.SetupSingleConnectionTest( out listener, out remote, // remote becomes client out local, // local becomes server port); } Assert.IsNotNull(local); Assert.IsNotNull(remote); }
//构造函数 public CSocket() { mState = SocketState.StateInit; ClearSocketErrorCode(); }
private void SendToClient(SocketState state, byte[] data) { if (state == null) return; if (state.Socket == null || !state.Socket.Connected) { state.Dispose(); state = null; return; } if (_socketSendCallback == null) _socketSendCallback = OnSent; try { state.Socket.BeginSend(data, 0, data.Length, SocketFlags.None, _socketSendCallback, state); } catch (SocketException e) { LogError(Category, "Error sending data"); LogError(Category, String.Format("{0} {1}", e.SocketErrorCode, e)); } }
/// <summary> /// Calback / prichod dat an streame /// </summary> /// <param name="ar">IAsyncResult</param> private void DataReceived(IAsyncResult ar) { lock (this) { //inicializacia SocketState state = (SocketState)ar.AsyncState; NetworkStream stream = state.Stream; Int32 r = 0; // kontrola ci mozme zo streamu citat if (!stream.CanRead) { return; } try { //prerusime asynchronne citanie r = stream.EndRead(ar); //ak neboli nacitane ziadne _data asi ide o pad spojenia if (r == 0) { //niekedy dochadza k oneskoreniu vlakna zo streamu ktory oznamuje pad spojenia if (this.IsDisposed == false) { //zalogujeme. this.InternalTrace(TraceTypes.Error, "Loss connection with the remote end point!"); //ukoncime komunikaciu this.InternalDisconnect(false); } //nebolo by vhodne nahodit t stav disconnected ??? return; } } catch (Exception ex) { //zalogujeme this.InternalException(ex, "Error during exiting asynchronous reading from the stream. {0}.", ex.Message); //ukoncime komunikaciu this.InternalDisconnect(false); //ukoncime return; } //skopirujeme pole bytov Byte[] rdata = new Byte[r]; Buffer.BlockCopy(state.Data, 0, rdata, 0, r); //zalogujeme prijate dat //this.InternalTrace(TraceTypes.Verbose, "Received _data: [{0}]", BitConverter.ToString(rdata)); this.InternalTrace(TraceTypes.Verbose, "Received data: [{0}]", rdata.Length); //_data su akeptovane len ak sme pripojeny if (this.IsConnected) { //vytvorime udalost a posleme data OnReceivedData(new DataEventArgs(rdata, state.Client.Client.RemoteEndPoint as IPEndPoint)); } try { //otvorime asynchronne citanie na streame stream.BeginRead(state.Data, 0, state.Data.Length, tcp_DataReceived, state); } catch (Exception ex) { //zalogujeme this.InternalTrace(TraceTypes.Error, "Chyba pri opatovnom spusteni asynchronneho citania zo streamu. {0}", ex.Message); //ukoncime return; } } }
private void OnCloseSocket(CloseType type, SocketState state, Exception e = null) { }
/// <summary> /// Interna snaha o pripojenie /// </summary> private void InternalOnConnect() { try { //zalogujeme this.InternalTrace(TraceTypes.Info, "Initializing socket..."); //ak inicializujeme triedu na zaklade IP a portu if (this.m_tcpClient == null) { //ziskame ipEndPoint na pripojenie this.m_lastIpEndPoint = this.GetIpEndPoint(); //inicializujeme a pripojime klienta this.m_tcpClient = new TcpClient(); this.m_tcpClient.Connect(this.m_lastIpEndPoint); } else { //adresa ku ktorej som pripojeny this.m_lastIpEndPoint = (IPEndPoint)this.m_tcpClient.Client.RemoteEndPoint; } //nastavime timeoty pre socket this.m_tcpClient.ReceiveTimeout = this.m_tcpReadTimeout; this.m_tcpClient.SendTimeout = this.m_tcpWriteTimeout; //ziskame komunikacny stream this.m_networkStream = m_tcpClient.GetStream(); this.m_networkStream.ReadTimeout = this.m_nsReadTimeout; this.m_networkStream.WriteTimeout = this.m_nsWriteTimeout; //inicializujeme state SocketState state = new SocketState() { Stream = this.m_networkStream, Client = this.m_tcpClient }; //zalogujeme this.InternalTrace(TraceTypes.Verbose, "Initialization socket was successful"); //nastavime detekciu spjenia this.m_isConnectied = true; //otvorime asynchronne citanie na streame this.m_networkStream.BeginRead(state.Data, 0, state.Data.Length, tcp_DataReceived, state); } catch (Exception ex) { //zalogujeme this.InternalException(ex, "Error during initializing socket. {0}", ex.Message); //nastavime detekciu spjenia this.m_isConnectied = false; this.m_tcpClient = null; this.m_networkStream = null; //preposleme vynimku throw; } }
///////////////////////////////////////////////////////////////////////////////////////// // Client-Side Code ///////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Begins the asynchronous process of connecting to a server via BeginConnect, /// and using ConnectedCallback as the method to finalize the connection once it's made. /// /// If anything goes wrong during the connection process, toCall should be invoked /// with a new SocketState with its ErrorOccured flag set to true and an appropriate message /// placed in its ErrorMessage field. Between this method and ConnectedCallback, toCall should /// only be invoked once on error. /// /// This connection process should timeout and produce an error (as discussed above) /// if a connection can't be established within 3 seconds of starting BeginConnect. /// /// </summary> /// <param name="toCall">The action to take once the connection is open or an error occurs</param> /// <param name="hostName">The server to connect to</param> /// <param name="port">The port on which the server is listening</param> public static void ConnectToServer(Action <SocketState> toCall, string hostName, int port) { // Establish the remote endpoint for the socket. IPHostEntry ipHostInfo; var ipAddress = IPAddress.None; // Determine if the server address is a URL or an IP try { ipHostInfo = Dns.GetHostEntry(hostName); bool foundIPV4 = false; foreach (var addr in ipHostInfo.AddressList) { if (addr.AddressFamily != AddressFamily.InterNetworkV6) { foundIPV4 = true; ipAddress = addr; break; } } // Didn't find any IPV4 addresses if (!foundIPV4) { HandleError(toCall, "Didn't find any IPV4 addresses"); return; } } catch (Exception) { // see if host name is a valid IP address try { ipAddress = IPAddress.Parse(hostName); } catch (Exception) { HandleError(toCall, "A host name is a invalid IP address"); return; } } // Create a TCP/IP socket. var socket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); // This disables Nagle's algorithm (Google if curious!) // Nagle's algorithm can cause problems for a latency-sensitive // game like ours will be socket.NoDelay = true; var socketState = new SocketState(toCall, socket); // Connect IAsyncResult ar; try { ar = socketState.Socket.BeginConnect(ipAddress, port, ConnectedCallback, socketState); } catch (Exception ex) { HandleError(socketState, ex.Message); return; } bool success = ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(3)); if (!success) { socketState.ErrorMessage = "timeout"; socket.Close(); // this closing action will trigger the error handling process in the callback. } }
void OnStateChange(SocketState state) { }
private bool ParseRequest(SocketState state, string message) { // \u0001\u0012\0\u0001\u0003\u0001\0\0\0whamdowfr\0whamdowfr\0.Ts,PRe`(groupid is null) AND (groupid > 0)\0\\hostname\\gamemode\\hostname\\hostport\\mapname\\password\\gamever\\numplayers\\maxplayers\\score_\\teamplay\\gametype\\gamevariant\\groupid\\numobservers\\maxobservers\\modname\\moddisplayname\\modversion\\devmode\0\0\0\0\u0004 // auto request // \03\0\u0001\u0003\u0001\0\0\0whammer40kdcam\0whammer40kdc\0tMU`s.kv\0\0\0\0\0\u0004 // chat rooms request // \0j\0\u0001\u0003\u0001\0\0\0whammer40kdc\0whammer40kdc\0}%D}s)<}\0\\hostname\\numwaiting\\maxwaiting\\numservers\\numplayersname\0\0\0\0 string[] data = message.Split(new char[] { '\x00' }, StringSplitOptions.RemoveEmptyEntries); //if (!data[2].Equals("whamdowfr", StringComparison.OrdinalIgnoreCase)) // return false; string validate = data[4]; string filter = null; bool isAutomatch = false; if (validate.Length > 8) { filter = validate.Substring(8); validate = validate.Substring(0, 8); } else { //Log(Category, "ROOMS REQUEST - "+ data[2]); isAutomatch = data[2].EndsWith("am"); if (!isAutomatch) { SendRooms(state, validate); return(true); } } var servers = _report.Servers.Values.Where(x => x.Valid).AsQueryable(); string[] fields = data[5].Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries); // May be real chat rooms: /*for (int i = 1; i <= 10; i++) * { * SendToClient(state, $@"\{i}\Room {i}\1\200\0\0\password\other\final\".ToAssciiBytes()); * }*/ // From bf2 server /*string gamename = data[1].ToLowerInvariant(); * string validate = data[2].Substring(0, 8); * string filter = FixFilter(data[2].Substring(8)); * string[] fields = data[3].Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);*/ //Log(Category, String.Format("Received client request: {0}:{1}", ((IPEndPoint)state.Socket.RemoteEndPoint).Address, ((IPEndPoint)state.Socket.RemoteEndPoint).Port)); // var server = JsonConvert.SerializeObject((object)_report.Servers.Values.FirstOrDefault() ?? ""); /*if (!String.IsNullOrWhiteSpace(filter)) * { * try * { * //Console.WriteLine(filter); * servers = servers.Where(filter); * //Console.WriteLine(servers.Count()); * } * catch (Exception e) * { * LogError(Category, "Error parsing filter"); * LogError(Category, filter); * LogError(Category, e.ToString()); * } * }*/ // http://aluigi.altervista.org/papers/gslist.cfg /*byte[] key; * key = DataFunctions.StringToBytes("hW6m9a"); * else if (gamename == "arma2oapc") * key = DataFunctions.StringToBytes("sGKWik"); * else * key = DataFunctions.StringToBytes("Xn221z");*/ byte[] unencryptedServerList = PackServerList(state, servers, fields, isAutomatch); byte[] encryptedServerList = GSEncoding.Encode(ChatServer.Gamekey, DataFunctions.StringToBytes(validate), unencryptedServerList, unencryptedServerList.LongLength); SendToClient(state, encryptedServerList); return(true); }
private static Task<int> ReceiveAsync(SocketState s, int offset, CancellationToken ct) { var tcs = new TaskCompletionSource<int>(s); s.Socket.BeginReceive(s.Buffer, offset, s.Buffer.Length, SocketFlags.None, (iar) => { var t = (TaskCompletionSource<int>)iar.AsyncState; var astate = (SocketState)t.Task.AsyncState; using (ct.Register(() => t.TrySetCanceled())) { try { t.TrySetResult(astate.Socket.EndReceive(iar)); } catch (Exception exc) { t.TrySetException(exc); } } }, tcs); return tcs.Task; }
private void SendRooms(SocketState state, string validate) { // d whamdowfr whamdowfr fkT>_2Cr \hostname\numwaiting\maxwaiting\numservers\numplayersname //var bytes = @"\fieldcount\8\groupid\hostname\numplayers\maxwaiting\numwaiting\numservers\password\other\309\Europe\0\50\0\0\0\.maxplayers.0\408\Pros\0\50\0\0\0\.maxplayers.0\254\West Coast 2\0\50\0\0\0\.maxplayers.0\255\West Coast 3\0\50\0\0\0\.maxplayers.0\256\East Coast 1\0\50\0\0\0\.maxplayers.0\257\East Coast 2\0\50\0\0\0\.maxplayers.0\253\West Coast 1\0\50\0\0\0\.maxplayers.0\258\East Coast 3\0\50\0\0\0\.maxplayers.0\407\Newbies\0\50\0\0\0\.maxplayers.0\final\".ToAssciiBytes(); //127 0 0 1 207 55 var bytes = new List <byte>(); // was ip IPEndPoint remoteEndPoint = ((IPEndPoint)state.Socket.RemoteEndPoint); bytes.AddRange(remoteEndPoint.Address.GetAddressBytes()); byte[] value2 = BitConverter.GetBytes((ushort)6500); bytes.AddRange(BitConverter.IsLittleEndian ? value2.Reverse() : value2); bytes.Add(5); // fields count bytes.Add(0); bytes.AddRange(DataFunctions.StringToBytes("hostname")); bytes.Add(0); bytes.Add(0); bytes.AddRange(DataFunctions.StringToBytes("numwaiting")); bytes.Add(0); bytes.Add(0); bytes.AddRange(DataFunctions.StringToBytes("maxwaiting")); bytes.Add(0); bytes.Add(0); bytes.AddRange(DataFunctions.StringToBytes("numservers")); bytes.Add(0); bytes.Add(0); bytes.AddRange(DataFunctions.StringToBytes("numplayersname")); bytes.Add(0); bytes.Add(0); // if (rooms == null) // { for (int i = 1; i <= 10; i++) { bytes.Add(81); var b2 = BitConverter.GetBytes((long)i); bytes.Add(b2[3]); bytes.Add(b2[2]); bytes.Add(b2[1]); bytes.Add(b2[0]); bytes.Add(0); bytes.Add(0); bytes.Add(255); bytes.AddRange(DataFunctions.StringToBytes("Room " + i)); bytes.Add(0); bytes.Add(255); bytes.AddRange(DataFunctions.StringToBytes(ChatServer.IrcDaemon.GetChannelUsersCount("#GPG!" + i).ToString())); bytes.Add(0); bytes.Add(255); bytes.AddRange(DataFunctions.StringToBytes("1000")); bytes.Add(0); bytes.Add(255); bytes.AddRange(DataFunctions.StringToBytes("1")); bytes.Add(0); bytes.Add(255); bytes.AddRange(DataFunctions.StringToBytes("20")); bytes.Add(0); } /*} * else * { * for (int i = 0; i < rooms.Length; i++) * { * var room = rooms[i]; * * bytes.Add(81); * * var b2 = BitConverter.GetBytes((long)i); * * bytes.Add(b2[3]); * bytes.Add(b2[2]); * bytes.Add(b2[1]); * bytes.Add(b2[0]); * * bytes.Add(0); * bytes.Add(0); * * bytes.Add(255); * bytes.AddRange(DataFunctions.StringToBytes(room.Name)); * bytes.Add(0); * * bytes.Add(255); * bytes.AddRange(DataFunctions.StringToBytes(room.Users.Count().ToString())); * bytes.Add(0); * * bytes.Add(255); * bytes.AddRange(DataFunctions.StringToBytes("2")); * bytes.Add(0); * * bytes.Add(255); * bytes.AddRange(DataFunctions.StringToBytes("1")); * bytes.Add(0); * * bytes.Add(255); * bytes.AddRange(DataFunctions.StringToBytes("20")); * bytes.Add(0); * } * }*/ bytes.AddRange(new byte[] { 0, 255, 255, 255, 255 }); var array = bytes.ToArray(); // var array = DataFunctions.StringToBytes("\u007f \0 \0 \u0001 \u0019 d \u0001 \0 hostname \0 \0 Q \u007f \0 \0 \u0001 \u0019 d ÿ Room 1 \0 \0 ÿÿÿÿ"); // working with Room 1 //var array = DataFunctions.StringToBytes("\u007f\0\0\u0001\u0019d\u0001\0hostname\0\0Q\u007f\0\0\u0001\u0019dÿRoom 1\0\0ÿÿÿÿ"); byte[] enc = GSEncoding.Encode(ChatServer.Gamekey, DataFunctions.StringToBytes(validate), array, array.LongLength); SendToClient(state, enc); }
private async void ReceiveData() { Debug.WriteLine("Net: ReceiveData"); var cts = new CancellationTokenSource(); ConnectionClosing += (sender, args) => cts.Cancel(); try { var z = new SocketState() { Socket = _client, Buffer = new byte[1024] }; while (true) { var t = ReceiveAsync(z, 0, cts.Token); var bytesRead = await t; if (bytesRead > 0) _netStates.Fire(NetEvent.Received, new ReceivedEventArgs { Bytes = z.Buffer.Take(bytesRead).ToArray() }); } } catch (OperationCanceledException e) { Debug.WriteLine(e.Message); } catch (Exception e) { _netStates.Fire(NetEvent.Error, e); } }
public static void SetSocketState(SocketState ss) { activeForm.SetSocketState(ss); }
private async void Send(byte[] data) { var cts = new CancellationTokenSource(); ConnectionClosing += (sender, args) => cts.Cancel(); var state = new SocketState() { Buffer = data, Socket = _client }; try { var t = await SendAsync(state, cts.Token); if (!t) throw new Exception("Data not send"); OnSendComplete(); } catch (OperationCanceledException e) { Debug.WriteLine("Sending cancelled"); } catch (Exception e) { var mes = "Error sending data: " + e; Debug.WriteLine(mes); _netStates.Fire(NetEvent.Error, e); } Debug.WriteLine("Net: Send Data"); }
void handleConnect(Socket s) { mSocket = s; mSocketState = SocketState.Ok; readPackageHeader(); //开始收包 }
private static Task<bool> SendAsync(SocketState state, CancellationToken ct) { var tcs = new TaskCompletionSource<bool>(state); state.Socket.BeginSend(state.Buffer, 0, state.Buffer.Length, SocketFlags.None, (iar) => { var t = (TaskCompletionSource<bool>)iar.AsyncState; var s = (SocketState)t.Task.AsyncState; using (ct.Register(() => t.TrySetCanceled())) { try { s.Socket.EndSend(iar); t.TrySetResult(true); } catch (Exception exc) { t.TrySetException(exc); } } }, tcs); return tcs.Task; }
public NetSockStateChangedEventArgs(SocketState newState, SocketState prevState) { this.NewState = newState; this.PrevState = prevState; }
public ClientGameMessage(SocketState client, ClientMessage message) { Client = client; Message = message; }
public Program() { System.Threading.Thread.Sleep(5000); theServer = Networking.ConnectToServer(FirstContact, Networking.IPResolve("localhost")); }
private void ConnectToServerCallback(SocketState ss) { socketState = ss; callback(); }
public ServerPlayer(SocketState state, GameManager gameManager) : base(state) { Id = Guid.NewGuid(); _gameManager = gameManager; }
public TcpClientStateEventArgs(string stateInfo, SocketState state) { StateInfo = stateInfo; State = state; }
///// <summary> ///// Send the message currently in our send buffer, starting at ///// the given byte offset and continuing for the given byte count. ///// </summary> ///// <param name="offset">The offset to start at in bytes.</param> ///// <param name="count">The number of bytes to send.</param> //private void SendMessage(int offset, int count) //{ // this.eventArgs.SetBuffer(offset, count); // bool asynchronous = this.socket.SendAsync(this.eventArgs); // if (!asynchronous) // { // this.IOCompleted(this, this.eventArgs); // } //} ///// <summary> ///// Send the message currently in our send buffer. ///// </summary> //private void SendMessage() //{ // this.SendMessage(0, this.bufferOffset); //} /// <summary> /// Start a receive operation. /// </summary> /// <param name="offset"> /// The offset into the receive buffer at which to start receiving. /// </param> /// <param name="max"> /// The maximum number of bytes to receive in this operation. /// </param> private void StartReceive(int offset, int max) { lock (this) { if (socketState == SocketState.Idle) { socketState = SocketState.Receiving; try { this.eventArgs.SetBuffer(buffer, offset, max); bool asynchronous = this.socket.ReceiveAsync(this.eventArgs); if (!asynchronous) { this.IOCompleted(this, this.eventArgs); } } catch (Exception ex) { Console.WriteLine("Caught exception in StartReceive: " + ex.ToString()); } } else { Console.WriteLine("Error: we shouldn't have come here!"); } } }
public TcpServerStateEventArgs(IClient iClient, string msg, SocketState state) { IClient = iClient; Msg = msg; State = state; }
/// <summary> /// Handler for the Completed event of an asynchronous socket operation. /// </summary> /// <param name="sender">The sender of this event.</param> /// <param name="ea">Arguments pertaining to this event.</param> private void IOCompleted(object sender, SocketAsyncEventArgs ea) { lock (this) { socketState = SocketState.Idle; if (ea.SocketError != SocketError.Success) { // - // If something failed, close the connection. // - this.ShutdownAndClose(); return; } if (ea.LastOperation == SocketAsyncOperation.Send) { // - // Send completed. // - int outstanding = ea.Count - ea.BytesTransferred; if (outstanding > 0) { // - // Still have data to send. // - //this.SendMessage( // ea.Offset + ea.BytesTransferred, // outstanding); SendRemainingBytes(ea.Offset, ea.BytesTransferred); return; } // - // still have more messages to send // - if (outgoingMessages.Count > 0) { TrySend(); return; } if (this.state == ConnectionState.ServiceRegistered) { // - // Once a peer has registered as a service, we only send it // match-up requests and never receive anything from it. // - return; } // - // Switch to receive mode. // - this.bufferOffset = 0; this.StartReceive(0, this.buffer.Length); } else { // - // Receive completed. // - if (ea.BytesTransferred == 0 || this.state == ConnectionState.ServiceRegistered) { // - // Our peer closed the connection. Reciprocate. // - this.ShutdownAndClose(); return; } // - // We have three cases to deal with at this point: // 1. We have a complete message from our peer. // 2. We have a partial message, // (a) and our receive buffer is full. // (b) and still have room in our receive buffer. // - int have = ea.Offset + ea.BytesTransferred - this.bufferOffset; int parsePoint = this.bufferOffset; while (have != 0) { MessageType type; byte length; // - // Check for special-case of a Pad1 message. // - type = (MessageType)this.buffer[parsePoint++]; have--; if (type == MessageType.Pad1) { this.bufferOffset = parsePoint; continue; } if (have > 0) { // - // We could potentially have a complete message. // - length = this.buffer[parsePoint++]; have--; if (have >= length) { // - // We have a complete message (as self-described). // - ArraySegment<byte> data; if (length == 0) { data = new ArraySegment<byte>(this.buffer, 0, 0); } else { data = new ArraySegment<byte>( this.buffer, parsePoint, length); parsePoint += length; have -= length; } if (this.HandleMessage(type, data)) { // - // We've switched out of receive mode. // Note: If 'have' is non-zero at this point, // our peer has violated the protocol. // - if (have != 0) { this.ShutdownAndClose(); } return; } // - // Still in receive mode, but handled a message. // - this.bufferOffset = parsePoint; continue; } } // - // We have a partial message. // - if (ea.Count == ea.BytesTransferred) { // - // Our receive buffer is full. Shift the start of // the current partial message down to the zero index. // - int partialLength = this.buffer.Length - this.bufferOffset; Array.Copy( this.buffer, this.bufferOffset, this.buffer, 0, partialLength); this.bufferOffset = 0; this.StartReceive( partialLength, this.buffer.Length - partialLength); return; } // - // Start another receive to fill in the buffer from where // the last one left off. // - this.StartReceive( ea.Offset + ea.BytesTransferred, ea.Count - ea.BytesTransferred); return; } // - // We had an integral number of messages (no partial messages). // We're expecting another message, so restart receive. // - this.bufferOffset = 0; this.StartReceive(0, this.buffer.Length); } } }
void ReceiveAsync(SocketState socketState) { socketState._socket.BeginReceive(socketState._rxBuffer, 0, socketState._rxBuffer.Length, SocketFlags.None, new AsyncCallback(ProcessRXData), socketState); }
public void Init() { testListener = null; testLocalSocketState = null; testRemoteSocketState = null; }
public void ExecuteProcessHandler(SocketState socketProcessTypes) { ProcessHandler?.Invoke(socketProcessTypes); }
private static byte[] PackServerList(SocketState state, IEnumerable<GameServer> servers, string[] fields) { IPEndPoint remoteEndPoint = ((IPEndPoint)state.Socket.RemoteEndPoint); byte[] ipBytes = remoteEndPoint.Address.GetAddressBytes(); byte[] value2 = BitConverter.GetBytes((ushort)6500); byte fieldsCount = (byte)fields.Length; List<byte> data = new List<byte>(); data.AddRange(ipBytes); data.AddRange(BitConverter.IsLittleEndian ? value2.Reverse() : value2); data.Add(fieldsCount); data.Add(0); foreach (var field in fields) { data.AddRange(DataFunctions.StringToBytes(field)); data.AddRange(new byte[] { 0, 0 }); } foreach (var server in servers) { // commented this stuff out since it caused some issues on testing, might come back to it later and see what's happening... // NAT traversal stuff... // 126 (\x7E) = public ip / public port / private ip / private port / icmp ip // 115 (\x73) = public ip / public port / private ip / private port // 85 (\x55) = public ip / public port // 81 (\x51) = public ip / public port /*Console.WriteLine(server.IPAddress); Console.WriteLine(server.QueryPort); Console.WriteLine(server.localip0); Console.WriteLine(server.localip1); Console.WriteLine(server.localport); Console.WriteLine(server.natneg); if (!String.IsNullOrWhiteSpace(server.localip0) && !String.IsNullOrWhiteSpace(server.localip1) && server.localport > 0) { data.Add(126); data.AddRange(IPAddress.Parse(server.IPAddress).GetAddressBytes()); data.AddRange(BitConverter.IsLittleEndian ? BitConverter.GetBytes((ushort)server.QueryPort).Reverse() : BitConverter.GetBytes((ushort)server.QueryPort)); data.AddRange(IPAddress.Parse(server.localip0).GetAddressBytes()); data.AddRange(BitConverter.IsLittleEndian ? BitConverter.GetBytes((ushort)server.localport).Reverse() : BitConverter.GetBytes((ushort)server.localport)); data.AddRange(IPAddress.Parse(server.localip1).GetAddressBytes()); } else if (!String.IsNullOrWhiteSpace(server.localip0) && server.localport > 0) { data.Add(115); data.AddRange(IPAddress.Parse(server.IPAddress).GetAddressBytes()); data.AddRange(BitConverter.IsLittleEndian ? BitConverter.GetBytes((ushort)server.QueryPort).Reverse() : BitConverter.GetBytes((ushort)server.QueryPort)); data.AddRange(IPAddress.Parse(server.localip0).GetAddressBytes()); data.AddRange(BitConverter.IsLittleEndian ? BitConverter.GetBytes((ushort)server.localport).Reverse() : BitConverter.GetBytes((ushort)server.localport)); } else {*/ data.Add(81); // it could be 85 as well, unsure of the difference, but 81 seems more common... data.AddRange(IPAddress.Parse(server.IPAddress).GetAddressBytes()); data.AddRange(BitConverter.IsLittleEndian ? BitConverter.GetBytes((ushort)server.QueryPort).Reverse() : BitConverter.GetBytes((ushort)server.QueryPort)); //} data.Add(255); for (int i = 0; i < fields.Length; i++) { data.AddRange(DataFunctions.StringToBytes(GetField(server, fields[i]))); if (i < fields.Length - 1) data.AddRange(new byte[] { 0, 255 }); } data.Add(0); } data.AddRange(new byte[] { 0, 255, 255, 255, 255 }); return data.ToArray(); }
public NetSockStateChangedEventArgs(SocketState newState, SocketState prevState) { this.NewState = newState; this.PrevState = prevState; }
private bool ParseRequest(SocketState state, string message) { string[] data = message.Split(new char[] { '\x00' }, StringSplitOptions.RemoveEmptyEntries); if (data.Length != 4 || (!data[0].Equals("civ4bts", StringComparison.InvariantCultureIgnoreCase) && !data[0].Equals("civ4btsjp", StringComparison.InvariantCultureIgnoreCase) && !data[0].Equals("civ4", StringComparison.InvariantCultureIgnoreCase)) || (!data[1].Equals("civ4bts", StringComparison.InvariantCultureIgnoreCase) && !data[1].Equals("civ4btsjp", StringComparison.InvariantCultureIgnoreCase) && !data[1].Equals("civ4", StringComparison.InvariantCultureIgnoreCase) && !data[1].Equals("gslive", StringComparison.InvariantCultureIgnoreCase))) { return false; } string gamename = data[1].ToLowerInvariant(); string validate = data[2].Substring(0, 8); string filter = "numplayers>-1";//Temporarily so that it shows all games //"gamemode=\"openstaging\"";//FixFilter(data[2].Substring(8)); string[] fields = data[3].Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries); Log(Category, String.Format("Received client request: {0}:{1}", ((IPEndPoint)state.Socket.RemoteEndPoint).Address, ((IPEndPoint)state.Socket.RemoteEndPoint).Port)); IQueryable<GameServer> servers = _report.Servers.ToList().Select(x => x.Value).Where(x => x.Valid).AsQueryable(); if (!String.IsNullOrWhiteSpace(filter)) { try { //Console.WriteLine(filter); servers = servers.Where(filter); //Console.WriteLine(servers.Count()); } catch (Exception e) { LogError(Category, "Error parsing filter"); LogError(Category, filter); LogError(Category, e.ToString()); } } // http://aluigi.altervista.org/papers/gslist.cfg byte[] key; key = DataFunctions.StringToBytes(Program.getGKey(gamename)); byte[] unencryptedServerList = PackServerList(state, servers, fields); byte[] encryptedServerList = GSEncoding.Encode(key, DataFunctions.StringToBytes(validate), unencryptedServerList, unencryptedServerList.LongLength); SendToClient(state, encryptedServerList); return true; }
/// <summary> /// Handler for when a client established a connection with the server. /// </summary> /// <param name="state"></param> private static void HandleNewClient(SocketState state) { state.ClientCallback = ReceivePlayerName; Networking.GetData(state); }
private void WaitForData(SocketState state) { Thread.Sleep(10); if (state == null || state.Socket == null || !state.Socket.Connected) return; try { if (_socketDataReceivedCallback == null) _socketDataReceivedCallback = OnDataReceived; state.Socket.BeginReceive(state.Buffer, 0, state.Buffer.Length, SocketFlags.None, _socketDataReceivedCallback, state); } catch (ObjectDisposedException) { state.Socket = null; } catch (SocketException e) { if (e.SocketErrorCode == SocketError.NotConnected) return; LogError(Category, "Error receiving data"); LogError(Category, String.Format("{0} {1}", e.SocketErrorCode, e)); return; } }
/// <summary> /// The main function driving the server almost entirely. Updates the world, then gets each object's info, /// adds it to the data to be sent to the clients, then sends it to all the clients. /// Any disconnected clients are also removed/dealt with. /// </summary> private static void Update() { if (watch.IsRunning) { // Make thread wait until the frame delay is met. while (watch.ElapsedMilliseconds < settings.GetMSPerFrame()) { Thread.Yield(); } watch.Restart(); // Update the world, and sent it as one to all clients. lock (theWorld) { theWorld.Update(); foreach (Ship ship in theWorld.GetShips().Values) { gameData.Append(ship.ToString() + "\n"); } foreach (Projectile proj in theWorld.GetProjectiles().Values) { gameData.Append(proj.ToString() + "\n"); } foreach (Star star in theWorld.GetStars().Values) { gameData.Append(star.ToString() + "\n"); } theWorld.Cleanup(); } // Iterate through the linked list of clients in order to remove any disconnected clients. lock (clients) { LinkedListNode <SocketState> firstNode = clients.First; while (firstNode != null) { SocketState socketState = firstNode.Value; Networking.SendSocket(socketState.theSocket, gameData.ToString()); if (!socketState.theSocket.Connected) { lock (theWorld) { if (theWorld.GetShips().ContainsKey(socketState.ID)) { theWorld.GetShips()[socketState.ID].MakeInactive(); } } LinkedListNode <SocketState> nextNode = firstNode.Next; clients.Remove(firstNode); firstNode = nextNode; } else { firstNode = firstNode.Next; } } } gameData.Clear(); } }