public void AcceptNewConnections() { LoginSocket.Listen(100); while (Continue) { Socket CSocket = null; try { CSocket = LoginSocket.Accept(); } catch (Exception e) { Console.WriteLine("Unable to accept a new connection, closing now."); LoginSocket.Close(); Console.WriteLine(e.StackTrace); } if (CSocket != null) { if (!CSocket.RemoteEndPoint.ToString().Contains(Configs.SITE_IP)) { ClientSocket CS = new ClientSocket(CSocket); new Thread(CS.Run).Start(); } else { CSocket.Close(); } } System.Threading.Thread.Sleep(200); } }
// Use this for initialization void Start() { client = new ClientSocket(new ExtendedClientHandshake() { Origin = "leap", Host = "localhost:6437", ResourcePath = "/get" }); client.Connect(); }
private static void BoltClientSocket() { _clientSocket = new ClientSocket(); _clientSocket.Connect("tcp://127.0.0.1:9900"); _clientSocket.MessageProcessor.MessageBroker.Subscribe<RequestMessage>(MessageHandler); _cancellationToken = new CancellationTokenSource(); Task.Factory.StartNew(SendMessages, _cancellationToken.Token); Console.ReadLine(); _clientSocket.Close(); }
// Use this for initialization void Start () { hudInstance = GameObject.Find ("UnityHUDPrefab"); if(hudInstance) { hudScript = hudInstance.GetComponent<HUD>(); } // This script must be attached to the sprite to work. anim = GetComponent<tk2dSpriteAnimator>(); InitAnimation(); clientSocketScript = GameObject.Find("PlayerConnection").GetComponent<ClientSocket>(); zooMapScript = GameObject.Find ("ZooMap").GetComponent<ZooMap>(); }
/// <summary> /// void to prcess all packets sent to the login server /// </summary> /// <param name="Data">packet byte array for handling</param> /// <param name="CSocket">client socket</param> public static void ProcessPacket(byte[] Data, ClientSocket CSocket) { int Type = (BitConverter.ToInt16(Data, 2)); switch (Type) { case 1060://login request { RequestLogin(Data, CSocket); break; } default: { Console.WriteLine("[LoginServer] Unknown packet type: " + Type); break; } } }
internal static GeneralResponsePackage GetPackage(ClientSocket socket) { try { var headerBytes = socket.Read(24); if (headerBytes == null) return null; var header = headerBytes.BytesToStruct<Header>(); var responseStatus = (ResponseStatus)header.Reserved; var extraBytes = header.ExtraLength > 0 ? socket.Read(header.ExtraLength) : null; var keyBytes = header.KeyLength > 0 ? socket.Read(header.KeyLength) : null; int valueCount = Convert.ToInt32(header.TotalBodyLength - header.KeyLength - header.ExtraLength); var valueBytes = valueCount > 0 ? socket.Read(valueCount) : null; Type t; List<KeyValuePair<Type, ResponsePackageAttribute>> pair = cmdTable.Where(item => Convert.ToByte(item.Value.Opcode) == header.Opcode).ToList(); if (pair.Count > 0) { t = pair.First().Key; } else { t = typeof(GeneralResponsePackage); } var package = Activator.CreateInstance(t) as GeneralResponsePackage; if (keyBytes != null) package.Key = Encoding.UTF8.GetString(keyBytes); package.ResponseStatus = responseStatus; package.Opcode = (Opcode)header.Opcode; package.ValueBytes = valueBytes; package.Version = header.Version; return package; } catch (Exception ex) { LocalLoggingService.Error(ex.ToString()); return null; } }
private void InitSocket() { ClientSocket = null; // Socket Stuff if (m_SocketConnectionType == SocketConnectionType.HttpPolling) { ClientSocket = new PollClientSocket(); } else if (m_SocketConnectionType == SocketConnectionType.Bosh) { ClientSocket = new BoshClientSocket(this); } else { ClientSocket = new ClientSocket(); } ClientSocket.OnConnect += SocketOnConnect; ClientSocket.OnDisconnect += SocketOnDisconnect; ClientSocket.OnReceive += SocketOnReceive; ClientSocket.OnError += SocketOnError; }
private void OnPlayerConnect(ClientSocket clientSocket, bool isReconnect) { if (!isReconnect) { _wssManager.DeviceIds.Remove(clientSocket.DeviceId); clientSocket.CloseSocket(); return; } var user = _gameManager.FindUserByDeviceId(clientSocket.DeviceId); if (user == null) { return; } user.UpdateClientSocketForReconnect(clientSocket); _playersByUser[user].Active = true; var position = _gameManager.FindUserPositionByClientSocket(user.ClientSocket); clientSocket.SendMessage(new StartGameMessage(position, _gameManager.GetAvatarList())); }
/// <summary> /// Делегат вызова подключения (калбэк) /// </summary> /// <param name="result"></param> private void ConnectCallback(IAsyncResult result) { try { ClientSocket.EndConnect(result); Buffer = new byte[SizeBuffer]; ConnectedStatus = true; CallConnected(); // Начинаем принимать сообщения ClientSocket.BeginReceive(Buffer, 0, Buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null); } catch (SocketException ex) { CallErrorClient(ClientErrorType.ConnectSocketError, ex.Message); Disconnect(); } catch (Exception ex) { CallErrorClient(ClientErrorType.ConnectSocketError, ex.Message); Disconnect(); } }
private void StartClient() { try { var ipHostInfo = Dns.GetHostEntry(ServerAddress); var ipaddress = ipHostInfo.AddressList[0]; var RemoteEP = new IPEndPoint(ipaddress, ServerPort); ClientSocket.BeginConnect(RemoteEP, new AsyncCallback(ConnectionCallBack), ClientSocket); ConnectDone.WaitOne(); SendDone.WaitOne(); Receive(ClientSocket); ReceiveDone.WaitOne(); } catch (Exception ex) { ErrorLogger.LogException(ex); } }
public void UploadClicked() { //if (!ClientSocket.connnetionSuccess) { // ErrorInfo.SetActive(true); // ErrorText.text = "You Are Not Playing Online!"; //} else { //List<GameInfoModel> RankList = UIManager.GetXMLInfo(); string msg = ""; if (difficulty == 0) { msg += "Easy " + score + " " + ((int)((Time.time - Difficulty.gameStartTime) * 1000)).ToString(); } else if (difficulty == 1) { msg += "Normal " + score + " " + ((int)((Time.time - Difficulty.gameStartTime) * 1000)).ToString(); } else if (difficulty == 2) { msg += "Scores " + score + " " + ((int)((Time.time - Difficulty.gameStartTime) * 1000)).ToString(); } ClientSocket.EncryptSend(msg); }
internal static void Send0x50(ClientSocket cs) { byte[] byteOne = new byte[1] { 1 }; SocketActions.SendData(cs, byteOne); Builder builder = new Builder(); builder.InsertInt32(0); builder.InsertString("68XI"); builder.InsertString(ReturnClient()); builder.InsertInt32(0xD3); builder.InsertInt32(0); builder.InsertInt32(0); builder.InsertInt32(0); builder.InsertInt32(0); builder.InsertInt32(0); builder.InsertNTString("USA"); builder.InsertNTString("United States"); builder.SendPacket(cs, 0x50); }
internal static void Process(ClientSocket userSocket, byte[] packet) { var msgLogin = (MsgLogin)packet; var username = msgLogin.GetUsername(); var password = msgLogin.GetPassword(); FConsole.WriteLine($"MsgLogin: {username} with password {password} (compressed: {msgLogin.Header.Compressed}) requesting login."); var user = new User { Socket = userSocket, Username = username, Password = password, Id = 1 }; //user.Socket.OnDisconnect += user.OnDisconnect; user.Socket.StateObject = user; msgLogin.UniqueId = user.Id; user.Send(msgLogin); }
/// <summary> /// Handles disconnection from the server. /// </summary> private void HandleDisconnection() { // Reset the socket SocketForceClose(); _Socket = new ClientSocket(); // Inform the player if (CurrentState == ClientState.BEFORE_SIGNING || CurrentState == ClientState.WAITING_FOR_START) { MessageBox.Show("Connection to the server is lost.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); _WaitingLobbyWindow.SetServerConnectingEnabled(true); _WaitingLobbyWindow.SetPlayerRegisteringEnabled(false); CurrentState = ClientState.BEFORE_CONNECTING; } else if (CurrentState == ClientState.GAME_IN_PLAY) { MessageBox.Show("Connection to the server is lost. Game has benn aborted.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); CurrentState = ClientState.GAME_ENDED; } }
/// <summary> /// Opens the websocket connection. /// </summary> /// <returns>IObservable<System.Boolean>.</returns> public IObservable <bool> Open() { return(Observable.Start(() => { if (ClientSocket.State != WebSocketState.Open) { var protocol = UseSsl ? "wss://" : "ws://"; var protocolPath = "/ws"; ClientSocket.ConnectAsync(new Uri(string.Concat(protocol, Domain, ":", Port, protocolPath)), CancellationToken.None) .GetAwaiter() .GetResult(); Uid = JsonConvert.DeserializeObject <WebsocketUid>(ReadSocket().Result); LoopReads = Task.Run(() => LoopRead(), _cToken.Token); Console.WriteLine("Connected to websocket via domain: " + Domain); } return Uid != null; })); }
private void onReceive() { Callback <ReturnValue <outputParameterType> > callback = Callback; ClientSocket socket = Socket; ReturnValue <outputParameterType> outputParameter = OutputParameter; InputParameter = default(inputParameterType); Callback = null; Socket = null; OutputParameter.Value = default(outputParameterType); if ((Interlocked.Increment(ref FreeLock) & 1) == 0) { free(); } try { callback.Call(ref outputParameter); } catch (Exception error) { socket.Log.Add(AutoCSer.Log.LogType.Error, error); } }
public void Ping(object obj) { lock (SendSync) { try { MsgPack msgpack = new MsgPack(); msgpack.ForcePathObject("Packet").AsString = "Ping"; msgpack.ForcePathObject("Message").AsString = "This is a ping!"; byte[] buffer = msgpack.Encode2Bytes(); byte[] buffersize = BitConverter.GetBytes(buffer.Length); ClientSocket.Poll(-1, SelectMode.SelectWrite); ClientSslStream.Write(buffersize, 0, buffersize.Length); ClientSslStream.Write(buffer, 0, buffer.Length); ClientSslStream.Flush(); } catch { Disconnected(); return; } } }
protected override void ReceiveCallback(IAsyncResult ar) { Log.Trace("ReceiveCallback"); try { byte[] buffer = (byte[])ar.AsyncState; int bytesRead = ClientSocket.EndReceive(ar); if (bytesRead > 0) { TResponsePacket packet = ISerializablePacket.FromBytes <TResponsePacket>(buffer); Log.Trace($"Received: {packet}"); OnMessageReceivedEvent(packet); } } catch (MessagePackSerializationException e) { Log.Warn(e, $"Could not deserialize MessagePack ({typeof(TResponsePacket).Name}) from received bytes"); } catch (Exception e) { Log.Error(e, "Error in data receiving"); } }
private void OnConnected(IAsyncResult ar) { try { RemoteSocket.EndConnect(ar); if (this.requestType == "CONNECT") { string respose = string.Format(ErrorPages.HTTPS_CONNECTED, this.httpVersion); ClientSocket.BeginSend(Encoding.ASCII.GetBytes(respose), 0, respose.Length, SocketFlags.None, this.OnRequestSent, ClientSocket); } else { string request = RebuildQuery(); Helper.Debug(request.Substring(0, request.IndexOf("\r\n") + 2), ConsoleColor.Green); RemoteSocket.BeginSend(Encoding.ASCII.GetBytes(request), 0, request.Length, SocketFlags.None, this.OnRequestSent, RemoteSocket); } } catch (Exception ex) { Dispose(); Helper.PublishException(ex); } }
public void RunServer() { props.Load(AppDomain.CurrentDomain.BaseDirectory + "config.properties"); socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); socket.Bind(new IPEndPoint(IPAddress.Any, int.Parse(props["server.port"]))); socket.Listen(int.Parse(props["server.backlog"])); logger.Info("Server Port: " + props["server.port"]); while (true) { ClientSocket client = new ClientSocket(); client.Socket = socket.Accept(); client.Session = Session; logger.Info("New Client: " + client.Socket.RemoteEndPoint.ToString()); Task task = new Task(client.HandleSocket); task.Start(); } }
private void onReceive() { Action <ReturnValue> callback = Callback; ClientSocket socket = Socket; InputParameter = default(inputParameterType); Callback = null; Socket = null; if ((Interlocked.Increment(ref FreeLock) & 1) == 0) { free(); } try { callback(new ReturnValue { Type = ReturnType }); } catch (Exception error) { socket.Log.Add(AutoCSer.Log.LogType.Error, error); } }
/// <summary> /// Reads the socket. /// </summary> /// <returns>Task<System.String>.</returns> internal async Task <string> ReadSocket() { var buffer = new ArraySegment <byte>(new byte[8192]); using (var stream = new MemoryStream()) { WebSocketReceiveResult result; do { result = await ClientSocket.ReceiveAsync(buffer, CancellationToken.None); stream.Write(buffer.Array, buffer.Offset, result.Count); }while (!result.EndOfMessage); stream.Seek(0, SeekOrigin.Begin); using (var reader = new StreamReader(stream)) { return(reader.ReadToEnd()); } } }
private void ReceiveCallback(IAsyncResult asyncResult) { try { int bytes = ClientSocket.EndReceive(asyncResult); if (bytes > 0) { lock (ReceiveDatas) { ReceiveDatas.Add(Encoding.UTF8.GetString(ClientBuffer, 0, bytes)); } ClientSocket.BeginReceive(ClientBuffer, 0, ClientBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null); } else { _Close(); } } catch (Exception) { _Close(); } }
///<summary>Called when we have sent data to the local client.<br>When all the data has been sent, we will start receiving again from the remote host.</br></summary> ///<param name="ar">The result of the asynchronous operation.</param> protected void OnClientSent(IAsyncResult ar) { lock (_bufferLock) { try { if (ClientSocket == null) { return; } int Ret = ClientSocket.EndSend(ar); if (Ret > 0) { if (OnClientSentEnd != null) { //OnClientSentEnd.BeginInvoke(ClientSocket, this, _cachedRemoteBufferHeaders, _cachedRemoteBuffer, false, null, null); OnClientSentEnd.Invoke(ClientSocket, this, _cachedRemoteBufferHeaders, _cachedRemoteBuffer.Count == 0 ? null : _cachedRemoteBuffer, false); } if (!Cancel) { DestinationSocket.BeginReceive(RemoteBuffer, 0, RemoteBuffer.Length, SocketFlags.None, new AsyncCallback(OnRemoteReceive), DestinationSocket); } else { Dispose(); } return; } } catch { } Dispose(); } }
private void OnReceiveQuery(IAsyncResult ar) { int Ret; try { Ret = ClientSocket.EndReceive(ar); } catch (Exception ex) { Log.Write(MethodInfo.GetCurrentMethod(), ex); Ret = -1; } if (Ret <= 0) { //Connection is dead :( Dispose(); return; } HttpQuery += Encoding.ASCII.GetString(Buffer, 0, Ret); //if received data is valid HTTP request... if (IsValidQuery(HttpQuery)) { ProcessQuery(HttpQuery); } else { try { ClientSocket.BeginReceive(Buffer, 0, Buffer.Length, SocketFlags.None, new AsyncCallback(this.OnReceiveQuery), ClientSocket); } catch (Exception ex) { Log.Write(MethodInfo.GetCurrentMethod(), ex); Dispose(); } } }
public static (List <Game>, string) LoadGames(string lastUpdate) { try { RequestMessage uploadRequestMessage = new RequestMessage { Username = Settings.Username, Password = Settings.Password, Request = "Load", Type = "Game", Content = lastUpdate, Time = DateTime.Now.ToString("HH:mm:ss dd") }; ClientSocket client = new ClientSocket(Settings.Ip, Settings.Port); client.SendMessage(uploadRequestMessage.ToString()); var update = new List <Game>(); var responses = GetResponses(ReceiveFullMsg(client)); foreach (var resp in responses) { if (!ResponseMessage.ToResponse(resp).Message.Equals("End")) { update.Add(Game.Deserialize(ResponseMessage.ToResponse(resp).Content)); } } return(update, DateTime.Now.ToString("HH:mm:ss dd")); } catch (SocketException) { return(null, lastUpdate); } catch (Exception) { return(null, lastUpdate); } }
void ReadClient(Socket client) { ClientSocket clientSocket = null; if (!m_ClientDic.TryGetValue(client, out clientSocket)) { return; } ReceiveState readBuff = clientSocket.ReceiveState; //接受信息,根据信息解析协议,根据协议内容处理消息再下发到客户端 if (readBuff.Stream.Position >= readBuff.Stream.Length) //如果上一次接收数据刚好收满 { OnReceiveData(clientSocket); } int count = 0; try { //count = client.Receive(readBuff.Bytes, readBuff.WriteIdx, readBuff.Remain, 0); count = client.Receive(readBuff.Stream.GetBuffer(), (int)readBuff.Stream.Position, (int)(readBuff.Stream.Length - readBuff.Stream.Position), SocketFlags.None); readBuff.Stream.Position += count; } catch (SocketException ex) { Debug.LogError("Receive fali:" + ex); CloseClient(clientSocket); return; } //代表客户端断开链接了 if (count <= 0) { CloseClient(clientSocket); return; } OnReceiveData(clientSocket); }
public void Disconnected() { if (LV != null) { if (Program.form1.listView1.InvokeRequired) { Program.form1.listView1.BeginInvoke((MethodInvoker)(() => { try { lock (Settings.Listview1Lock) LV.Remove(); if (LV2 != null) { lock (Settings.Listview3Lock) LV2.Remove(); } } catch { } })); } lock (Settings.Online) Settings.Online.Remove(this); } try { ClientSslStream?.Close(); ClientSocket?.Close(); ClientSslStream?.Dispose(); ClientSocket?.Dispose(); ClientMS?.Dispose(); } catch { } }
public override void Send(byte[] data, string to = "") { if (!string.IsNullOrEmpty(to)) { var strings = to.Split(':'); try { var ipAddress = IPAddress.Parse(strings[0]); var port = int.Parse(strings[1]); _endPoint = new IPEndPoint(ipAddress, port); _listening = false; } catch (Exception e) { OnCaughtException(e, EventCode.Other); return; } } try { ClientSocket.BeginSendTo(data, 0, data.Length, 0, _endPoint, OnSendToCallback, ClientSocket); OnReportingStatus(StatusCode.Info, $"Started sending {data.Length} bytes to {_endPoint} via UDP socket"); } catch (ObjectDisposedException) { } catch (SocketException socketException) { OnCaughtException(socketException, EventCode.Send); } catch (Exception e) { OnCaughtException(e, EventCode.Other); } }
///<summary>Called when we have sent data to the remote host.<br>When all the data has been sent, we will start receiving again from the local client.</br></summary> ///<param name="ar">The result of the asynchronous operation.</param> protected void OnRemoteSent(IAsyncResult ar) { try { int Ret = DestinationSocket.EndSend(ar); if (Ret > 0) { ClientSocket.BeginReceive(Buffer, 0, Buffer.Length, SocketFlags.None, new AsyncCallback(this.OnClientReceive), ClientSocket); if (CompleteSendBuffer.Length > 0) { if (OnDataReceived != null) { try { OnDataReceived(CompleteSendBuffer, CompleteReadBuffer); } catch (Exception) { } } CompleteReadBuffer = string.Empty; CompleteSendBuffer = string.Empty; Dispose(); return; } else { CompleteSendBuffer += System.Text.Encoding.ASCII.GetString(Buffer, 0, Buffer.Length); } return; } } catch { } Dispose(); }
/// <summary> /// Sends copy of buffer synchronously (blocking) /// </summary> /// <returns>Returns false if send fails, else returns true</returns> protected bool SendCopy(byte[] buffer, int offset, int count, SocketFlags socketFlags) { if (SendShutdowned()) { return(false); } var rentedBuffer = ArrayPool <byte> .Shared.Rent(count); Buffer.BlockCopy(buffer, offset, rentedBuffer, 0, count); try { int sent = ClientSocket.Send(rentedBuffer, 0, count, socketFlags); while (sent < count) { sent += ClientSocket.Send(rentedBuffer, sent, count - sent, socketFlags); } return(true); } catch (SocketException ex) { HandleSendSocketError(ex.SocketErrorCode).GetAwaiter().GetResult(); return(false); } catch (ObjectDisposedException) { HandleClose().GetAwaiter().GetResult(); return(false); } finally { ArrayPool <byte> .Shared.Return(rentedBuffer); } }
public void Dispose() { try { if (ClientSocket != null) { ClientSocket.Shutdown(SocketShutdown.Both); } } catch { } try { if (DestinationSocket != null) { DestinationSocket.Shutdown(SocketShutdown.Both); } } catch { } if (ClientSocket != null) { ClientSocket.Close(); } if (DestinationSocket != null) { DestinationSocket.Close(); } ClientSocket = null; DestinationSocket = null; if (_destroyer != null) { _destroyer(this); } }
///<summary>Disposes of the resources (other than memory) used by the Client.</summary> ///<remarks>Closes the connections with the local client and the remote host. Once <c>Dispose</c> has been called, this object should not be used anymore.</remarks> ///<seealso cref ="System.IDisposable"/> public void Dispose() { try { ClientSocket.Shutdown(SocketShutdown.Both); } catch {} try { DestinationSocket.Shutdown(SocketShutdown.Both); } catch {} //Close the sockets try { if (ClientSocket != null) { ClientSocket.Close(); } } catch { } try { if (DestinationSocket != null) { DestinationSocket.Close(); } } catch { } //Clean up ClientSocket = null; DestinationSocket = null; try { if (Destroyer != null) { Destroyer(this); } } catch { } }
public Request(Context ctx, ClientSocket cs) { _ctx = ctx; _cs = cs; _cs.RegisterRequest(S2cProtocol.handshake.Tag, handshake); _cs.RegisterRequest(S2cProtocol.match.Tag, match); _cs.RegisterRequest(S2cProtocol.join.Tag, join); _cs.RegisterRequest(S2cProtocol.leave.Tag, leave); _cs.RegisterRequest(S2cProtocol.afk.Tag, afk); _cs.RegisterRequest(S2cProtocol.authed.Tag, authed); _cs.RegisterRequest(S2cProtocol.ready.Tag, ready); _cs.RegisterRequest(S2cProtocol.shuffle.Tag, shuffle); _cs.RegisterRequest(S2cProtocol.dice.Tag, dice); _cs.RegisterRequest(S2cProtocol.deal.Tag, deal); _cs.RegisterRequest(S2cProtocol.take_xuanpao.Tag, take_xuanpao); _cs.RegisterRequest(S2cProtocol.take_xuanque.Tag, take_xuanque); _cs.RegisterRequest(S2cProtocol.xuanpao.Tag, xuanpao); _cs.RegisterRequest(S2cProtocol.xuanque.Tag, xuanque); _cs.RegisterRequest(S2cProtocol.call.Tag, call); _cs.RegisterRequest(S2cProtocol.take_turn.Tag, take_turn); _cs.RegisterRequest(S2cProtocol.peng.Tag, peng); _cs.RegisterRequest(S2cProtocol.gang.Tag, gang); _cs.RegisterRequest(S2cProtocol.hu.Tag, hu); _cs.RegisterRequest(S2cProtocol.lead.Tag, lead); _cs.RegisterRequest(S2cProtocol.over.Tag, over); _cs.RegisterRequest(S2cProtocol.settle.Tag, settle); _cs.RegisterRequest(S2cProtocol.final_settle.Tag, final_settle); _cs.RegisterRequest(S2cProtocol.restart.Tag, restart); _cs.RegisterRequest(S2cProtocol.take_restart.Tag, take_restart); _cs.RegisterRequest(S2cProtocol.rchat.Tag, rchat); _cs.RegisterRequest(S2cProtocol.radio.Tag, radio); }
/// <summary> /// Sends copy of buffer synchronously (blocking) /// </summary> /// <returns>Returns false if send fails, else returns true</returns> protected bool SendCopy(ReadOnlySpan <byte> span, SocketFlags socketFlags) { if (SendShutdowned()) { return(false); } var rentedBuffer = ArrayPool <byte> .Shared.Rent(span.Length); span.CopyTo(rentedBuffer); try { int sent = ClientSocket.Send(rentedBuffer, 0, span.Length, socketFlags); while (sent < span.Length) { sent += ClientSocket.Send(rentedBuffer, sent, span.Length - sent, socketFlags); } return(true); } catch (SocketException ex) { HandleSendSocketError(ex.SocketErrorCode).GetAwaiter().GetResult(); return(false); } catch (ObjectDisposedException) { HandleClose().GetAwaiter().GetResult(); return(false); } finally { ArrayPool <byte> .Shared.Return(rentedBuffer); } }
void Start() { socket = ClientSocket.Socket(); infoMessage = Resources.Load <GameObject>("Prefabs/infoMessage"); serverStatus = GameObject.Find("serverStatus").GetComponent <Text>(); buttonSignIn = GameObject.Find("button_signin").GetComponent <Button>(); buttonRegister = GameObject.Find("button_register").GetComponent <Button>(); socket.io.On("build_game", (SocketIOEvent e) => { ServerData serverData = JsonMapper.ToObject <ServerData>(e.data); socket.game_resources = new Game_Resources(); socket.game_data = new Game_Data(socket.game_resources, serverData); socket.player_local = new Player_Local(serverData.player_data, socket.game_data); if (socket.player_local != null) { socket.changeScene("game"); } }); setLanguage(); }
public void WriteToBuffer(IAsyncResult ar) { try { int revCount = ClientSocket.EndReceive(ar); if (revCount > 0) { Byte[] a = new Byte[revCount]; //byte[] buff = Connections.Find(x => x.ClientSocket == client).buff; //IEnumerable<Connection> query = Connections.Where(x => x.ClientSocket == client); Buffer.BlockCopy(buff, 0, a, 0, revCount); cb.Write(a, 0, a.Length); } ClientSocket.BeginReceive(buff, 0, buff.Length, SocketFlags.None, new AsyncCallback(WriteToBuffer), ClientSocket); BufferDataIn(); } catch (SocketException ex) { parent.OnDebug(eDebugEventType.Info, "SocketException: {0} ", ex.ErrorCode); switch (ex.ErrorCode) { case 10053: // An established connection was aborted by the software in your host machine parent.OnDebug(eDebugEventType.Info, "Software caused connection abort"); Disconnect(ClientSocket); break; case 10054: // An existing connection was forcibly closed by the remote host. parent.OnDebug(eDebugEventType.Info, "Connection reset by peer"); Disconnect(ClientSocket); break; } } finally { } }
public void TestSelect1 () { Socket srv = CreateServer (); ClientSocket clnt = new ClientSocket (srv.LocalEndPoint); Thread th = new Thread (new ThreadStart (clnt.ConnectSleepClose)); Socket acc = null; try { th.Start (); acc = srv.Accept (); clnt.Write (); ArrayList list = new ArrayList (); ArrayList empty = new ArrayList (); list.Add (acc); Socket.Select (list, empty, empty, 100); Assertion.AssertEquals ("#01", 0, empty.Count); Assertion.AssertEquals ("#02", 1, list.Count); Socket.Select (empty, list, empty, 100); Assertion.AssertEquals ("#03", 0, empty.Count); Assertion.AssertEquals ("#04", 1, list.Count); Socket.Select (list, empty, empty, -1); Assertion.AssertEquals ("#05", 0, empty.Count); Assertion.AssertEquals ("#06", 1, list.Count); } finally { if (acc != null) acc.Close (); srv.Close (); } }
public void TestSelect1 () { Socket srv = CreateServer (); ClientSocket clnt = new ClientSocket (srv.LocalEndPoint); Thread th = new Thread (new ThreadStart (clnt.ConnectSleepClose)); Socket acc = null; try { th.Start (); acc = srv.Accept (); clnt.Write (); ArrayList list = new ArrayList (); ArrayList empty = new ArrayList (); list.Add (acc); Socket.Select (list, empty, empty, 100); Assert.AreEqual (0, empty.Count, "#01"); Assert.AreEqual (1, list.Count, "#02"); Socket.Select (empty, list, empty, 100); Assert.AreEqual (0, empty.Count, "#03"); Assert.AreEqual (1, list.Count, "#04"); Socket.Select (list, empty, empty, -1); Assert.AreEqual (0, empty.Count, "#05"); Assert.AreEqual (1, list.Count, "#06"); // Need to read the 10 bytes from the client to avoid a RST byte [] bytes = new byte [10]; acc.Receive (bytes); } finally { if (acc != null) acc.Close (); srv.Close (); } }
public void AyncTcpServer() { ServerSocket serverSocket = new ServerSocket(); serverSocket.Bind(9900); serverSocket.AddMessageHandler<SampleMessage>(SampleMessageHandler); // Get host related information. IPAddress[] addressList = Dns.GetHostEntry(Environment.MachineName).AddressList; // Get endpoint for the listener. IPEndPoint localEndPoint = new IPEndPoint(addressList[addressList.Length - 1], 9900); long totalTime = 0; const int msgs = (int)1e5; int msgLength = 0; Action action = () => { ClientSocket clientSocket = new ClientSocket(); clientSocket.Connect(localEndPoint); Assert.IsTrue(clientSocket.Connected); Stopwatch sw = Stopwatch.StartNew(); Serializer serializer = new Serializer(); var sample = new SampleMessage { X = 38 }; var msg = serializer.Serialize(sample); msgLength = msg.Length; for (int i = 0; i < msgs; i++) { clientSocket.Send(sample); } sw.Stop(); Interlocked.Add(ref totalTime, sw.ElapsedMilliseconds); SpinWait.SpinUntil(() => counter == msgs, 2000); //networkStream.Close(); clientSocket.Close(); }; List<Action> actions = new List<Action>(); int numOfClients = 1; for (int i = 0; i < numOfClients; i++) { actions.Add(action); } Stopwatch sw2 = Stopwatch.StartNew(); Parallel.Invoke(actions.ToArray()); if (!Debugger.IsAttached) SpinWait.SpinUntil(() => counter == msgs * numOfClients, 2000); else { SpinWait.SpinUntil(() => counter == msgs * numOfClients, 60000); } sw2.Stop(); Console.WriteLine("Num Of Msgs: {0:###,###}", counter); Console.WriteLine("Average for each client {0}ms", totalTime / actions.Count); Console.WriteLine("Average Speed for each client: {0:###,###}msgs/s", (msgs / (totalTime / actions.Count)) * 1000); Console.WriteLine("Total time: {0}ms", sw2.ElapsedMilliseconds); Console.WriteLine("Msgs/s {0:###,###}", (counter / sw2.ElapsedMilliseconds) * 1000); Console.WriteLine("Msg length {0}bytes", msgLength); Assert.AreEqual(msgs * numOfClients, counter, "Not all msgs received"); }
public void JoinServer(string username, string pw, string ip, int port) { Connected = true; Model.ClientModel.Username = username; Model.ClientModel.Password = pw; ClientSocket = new ClientSocket(this, ip, port); ClientSocket.IncomingMessage += IncomingMessage; ClientSocket.UserConnect += UserJoin; ClientSocket.UserDisconnect += UserLeave; View.AddInfoInfo("Connected to "+ip+":"+port); }
private ClientSocket Connect() { lock (this) { if (_maxConnections <= _activeCount + _startingCount) return null; _startingCount++; } State state = _state; if (! state.isInit()) { String message = String.Format("'{0}' connection cannot be opened because the server pool has not been started.", this); InvalidOperationException e = new InvalidOperationException(message); _log.Warning(message); throw e; } try { ReadWritePair pair = openTCPPair(); ReadStream rs = pair.getReadStream(); rs.setAttribute("timeout", new Integer((int) _loadBalanceSocketTimeout)); synchronized (this) { _activeCount++; _connectCountTotal++; } ClientSocket stream = new ClientSocket(this, _streamCount++, rs, pair.getWriteStream()); if (log.isLoggable(Level.FINER)) log.finer("connect " + stream); if (_firstSuccessTime <= 0) { if (_state.isStarting()) { if (_loadBalanceWarmupTime > 0) _state = State.WARMUP; else _state = State.ACTIVE; _firstSuccessTime = Alarm.getCurrentTime(); } if (_warmupState < 0) _warmupState = 0; } return stream; } catch (IOException e) { if (_log.IsLoggable()) _log.log(Level.FINEST, this + " " + e.toString(), e); else log.finer(this + " " + e.toString()); failConnect(); return null; } finally { synchronized (this) { _startingCount--; } } }
void Awake() { serverConnection = GameObject.Find ("PlayerConnection").GetComponent<ClientSocket>(); switch(m_currentScene) { case SceneType.Start: serverConnection.ForceDisconnect(); Debug.Log ("Start scene"); break; case SceneType.MainMenu: Debug.Log ("Main Menu scene"); break; case SceneType.Lobby: Debug.Log ("Lobby scene"); GameObject zooMap = GameObject.Find("ZooMap"); if(zooMap != null) zooMap.GetComponent<ZooMap>().StartZooMap(); DisplayLobby(); break; case SceneType.GameRoom: Debug.Log ("Game Room scene"); DisplayRoom(); break; case SceneType.Game: Debug.Log ("Game scene"); break; } }
private void Awake() { mInstance = this; }
/// <summary> /// Method to handle Login Requests /// </summary> /// <param name="Data">Packet in byte array</param> /// <param name="CSocket">Client Socket</param> public static void RequestLogin(byte[] Data, ClientSocket CSocket) { string AccountName = ""; string Password = ""; string ServerName = ""; if (Data.Length >= 276) { for (int i = 4; i < 0x114; i++) { if (i >= 0x14 && i < 0xf9) { if (Data[i] != 0x00) Password += Convert.ToChar(Data[i]); } if (i < 0x14) if (Data[i] != 0x00) AccountName += Convert.ToChar(Data[i]); if (i > 0xfa) if (Data[i] != 0x00) ServerName += Convert.ToChar(Data[i]); } } else { return; } System.Random Random = new System.Random(); Console.WriteLine("[LoginServer] " + AccountName + " logging in to " + ServerName); string DBPass = Database.Database.Password(AccountName); if (DBPass != "ERROR") { if (DBPass == Password) { //A ban Check could be put here uint Key = (uint)(Random.Next(10000000)); Key = Key << 32; Key = Key << 32; Key = (uint)(Key | (uint)Random.Next(10000000)); byte[] Key1 = new byte[4]; byte[] Key2 = new byte[4]; Key1[0] = (byte)(((ulong)Key & 0xff00000000000000L) >> 56); Key1[1] = (byte)((Key & 0xff000000000000) >> 48); Key1[2] = (byte)((Key & 0xff0000000000) >> 40); Key1[3] = (byte)((Key & 0xff00000000) >> 32); Key2[0] = (byte)((Key & 0xff000000) >> 24); Key2[1] = (byte)((Key & 0xff0000) >> 16); Key2[2] = (byte)((Key & 0xff00) >> 8); Key2[3] = (byte)(Key & 0xff); if (ServerName == "ghost") { if (AuthSocket.Authorize(AccountName, Key))//checks if the sending to the game server is successful (no error check atm so if it fails to send there will be an error) { CSocket.Send(Packets.AuthResponse("127.0.0.1", Key1, Key2)); } else { Console.WriteLine("Unable to send client data to gameserver"); CSocket.Send(Packets.ErrorMessage("Game Server is down")); Console.WriteLine("Disconnecting client"); CSocket.Disconnect(); } } else { Console.WriteLine("Client used the server name \"" + ServerName + "\" but this server is not on the connectable list"); Console.WriteLine("Disconnecting client"); CSocket.Disconnect(); } } //This has not been set for EO yet but is kept from the base source as it could be used in the future //This will set the Password for the account when it logs in for the first time to the password which is entered /*else if (DBPass == "") { Console.WriteLine("[LoginServer](Diagnostic) Set password for " + AccountName); Database.Database.SetPass(AccountName, Password); //OKAY to login! uint Key = (uint)(Random.Next(10000000) << 32); Key = Key << 32; Key = (uint)(Key | (uint)Random.Next(10000000)); byte[] Key1 = new byte[4]; byte[] Key2 = new byte[4]; Key1[0] = (byte)(((ulong)Key & 0xff00000000000000L) >> 56); Key1[1] = (byte)((Key & 0xff000000000000) >> 48); Key1[2] = (byte)((Key & 0xff0000000000) >> 40); Key1[3] = (byte)((Key & 0xff00000000) >> 32); Key2[0] = (byte)((Key & 0xff000000) >> 24); Key2[1] = (byte)((Key & 0xff0000) >> 16); Key2[2] = (byte)((Key & 0xff00) >> 8); Key2[3] = (byte)(Key & 0xff); if (ServerName == "ghost") { if (AuthSocket.Authorize(AccountName, Key, false))//checks if the sending to the game server is successful (no error check atm so if it fails to send there will be an error) { CSocket.Send(Packets.AuthResponse("127.0.0.1", Key1, Key2)); } else { Console.WriteLine("Unable to send client data to gameserver"); Console.WriteLine("Disconnecting client"); } } else { Console.WriteLine("Client used the server name \"" + ServerName + "\" but this server is not on the connectable list"); Console.WriteLine("Disconnecting client"); CSocket.Disconnect(); } }*/ else { Console.WriteLine("Client entered the wrong password"); CSocket.Send(Packets.WrongPass()); CSocket.Disconnect(); } } else { Console.WriteLine("DBPass equals ERROR: " + DBPass); CSocket.Disconnect(); } }
void ClientWebSocket_DataReceived(ClientSocket sender, SocketEventArgs e) { try { if (e.Source.OpCode == OpCode.Ping) { DoPing(e); } else if (e.Source.OpCode == OpCode.Pong) { DoPong(e); } else { TriggerMessage(e); } } catch (Exception) { } }
/// <summary> /// /// </summary> /// <param name="remoteEndPoint"></param> /// <param name="route">远端执行方法名</param> /// <param name="param">参数</param> /// <param name="bufferSize"></param> protected void DoRequest(IPEndPoint remoteEndPoint, string param, int bufferSize) { client = new ClientSocket(new ClientSocketSettings(1024, remoteEndPoint)); client.Disconnected += DoDisconnected; client.DataReceived += DoReceive; client.Connect(); byte[] data = Encoding.UTF8.GetBytes("?d="+param); client.PostSend(data, 0, data.Length); if (!client.WaitAll(10000)) { DoError("请求超时"); } }