private void AcceptTcpConnections() { _tcpListener.Start(); while (true) { try { var tcpClient = _tcpListener.AcceptTcpClient(); var tcpClientHandler = new TcpClientHandler(tcpClient) { RecievedMessageHandler = ProcessRequest }; _tcpConnectionHandlers.Add(tcpClientHandler); tcpClientHandler.StartService(); } catch (InvalidOperationException e) { Console.WriteLine(e); return; } } _tcpListener.Stop(); }
private static void StartBbsServer() { IPAddress ipAddress = IPAddress.Any; // IPAddress.Parse("127.0.0.1"); int port = 6400; TcpListener tcpListener = new TcpListener(ipAddress, port); Console.Write("Starting TCP server on port " + port.ToString() + "... "); tcpListener.Start(); Console.WriteLine(" DONE!"); int ConnectionCount = 0; while (true) { //using (TcpClient tcpClient = tcpListener.AcceptTcpClient()) TcpClient tcpClient = tcpListener.AcceptTcpClient(); Console.WriteLine("New client connection!"); ConnectionCount++; Console.WriteLine("Connection #" + ConnectionCount.ToString() + " is established and awaiting data..."); //NetworkStreamHandler NSH = new NetworkStreamHandler(tcpClient.GetStream(), ConnectionCount); TcpClientHandler TCH = new TcpClientHandler(tcpClient, ConnectionCount); //Console.WriteLine("Client connection closed."); } }
public bool sendToClient(TcpClientHandler client, BufferStream buff) { if (client != null && buff != null) { try { if (client.Connected && client.Receiver.Connected && client.Stream.CanWrite) { PacketStream.SendAsync(client, buff); return(true); } } catch (System.IO.IOException) { mainProgram.WriteLine("error-writing to stream for socket " + client.Socket.ToString() + Environment.NewLine + " probably failed, trying again"); return(sendToClient(client, buff)); } } else { if (client == null) { mainProgram.WriteLine("error-inputted client is null"); } if (buff == null) { mainProgram.WriteLine("error-inputted buffer is null"); } } return(false); }
private static TcpClientHandler event_clientCreated(SocketBinder binder, TcpServerHandler server, uint clientTimeout) { TcpClientHandler tmp_ = new TcpClientHandler(binder, server, clientTimeout); mainProgram.WriteLine("Client " + tmp_.Socket.ToString() + " has been created"); return(tmp_); }
private static void event_disconnected(TcpClientHandler client) { mainProgram.WriteLine("Client " + client.Socket.ToString() + " disconnected from " + getIp(client).ToString()); int id_ = gameWorld.getPlayer(client.Socket); gameWorld.removeClient(id_); }
public async Task <bool> ConnectAsync() { if (m_ip == null) { throw new InvalidOperationException("Can not connect to a server if no Ip address is specified"); } if (IsConnected) { throw new InvalidOperationException("Le client est déjà connecté"); } m_client = new TcpClientHandler(m_ip, m_port); bool isSuccessful = await m_client.ConnectAsync(); if (isSuccessful) { m_isConnected = true; m_client.Disconnected += m_client_Disconnected; m_client.ReceivedFull += m_client_ReceivedFull; return(true); } m_isConnected = false; m_client = null; return(false); }
public void GivenEmptyTcpClient_WhenCreatingHandler_FailOnDisconnectedClient() { var client = new TcpClientHandler(new TcpClient()); var ex = Assert.Throws <InvalidOperationException>(() => new ChatScriptHandler(client)); Assert.AreEqual("Client not connected", ex.Message); }
static void ProcessReceiveResults(IAsyncResult ar) { TcpClientHandler TCH = (TcpClientHandler)ar.AsyncState; try { int BytesRead = 0; BytesRead = TCH.TcpClient.GetStream().EndRead(ar); //Console.WriteLine("Connection " + TCH.ConnectionId.ToString() + " received " + BytesRead.ToString() + " byte(s)."); if (BytesRead == 0) { //Console.WriteLine("Connection " + TCH.ConnectionId.ToString() + " is closing."); //NSH.NetworkStream.Close(); TCH.Close(); DateTime dtEnd = DateTime.Now; return; } else { string Data = System.Text.Encoding.GetEncoding(28591).GetString(TCH.Buffer); //Console.Write(Data); foreach (char DataCharIn in Data) { TCH.ProcessDataReceived(DataCharIn); } } if (TCH.Connected == true) { TCH.Buffer = new byte[BufferSize]; TCH.TcpClient.GetStream().BeginRead(TCH.Buffer, 0, TCH.Buffer.Length, TCH.AsyncReceiveCallback, TCH); } } catch (Exception e) { if (TCH.Connected == true) { Console.WriteLine("Failed to read from a network stream with error: " + e.Message); //TCH.NetworkStream.Close(); TCH.Close(); } } }
void m_client_Disconnected(object sender, TcpEventArgs e) { m_client = null; if (OnDisconnected != null) { OnDisconnected(this, e); } }
public void Protocol_Logic(IProtocol protocol, TcpClientHandler handler) { Action <IProtocol, TcpClientHandler> action; if (HandlePool.TryGetValue(protocol.GetProtocol_ID(), out action)) { action(protocol, handler); } }
private void m_client_Disconnected(object sender, TcpEventArgs e) { m_isConnected = false; if (OnDisconnected != null) { OnDisconnected(this, e); } m_client = null; }
private SendMessageResponse SendMessageToChatScript(string text) { try { var map = GetNode <Map>("/root/Map"); var request = new SendMessageRequest { UserCookieId = map.User.CookieId.ToString(), BotName = BotName, Message = text, InputData = JsonConvert.SerializeObject(map.User?.Facts?.Split(',').ToList() ?? new List <string>()) }; SendMessageResponse response; if (OS.HasFeature("JavaScript")) { string javaScript = @" var sendMessageRequest = " + JsonConvert.SerializeObject(request) + @"; parent.SendMessageToChatScript(sendMessageRequest); " ; string jsResponse = JavaScript.Eval(javaScript).ToString(); response = JsonConvert.DeserializeObject <SendMessageResponse>(jsResponse); } else { var tcpClient = new TcpClient("localhost", 1024); using (ITcpClient client = new TcpClientHandler(tcpClient)) { var chatScript = new ChatScriptHandler(client); response = chatScript.SendMessage(request, GetNode <Map>("/root/Map").Context); } } if (response.NewFacts != null && response.NewFacts.Length > 0) { EmitSignal(nameof(NewFacts), new[] { response.NewFacts }); _oldFacts = GetNode <Map>("/root/Map").User?.Facts?.Split(',').ToList() ?? new List <string>(); } _lastResponse = response; return(response); } catch (Exception ex) { throw; return(new SendMessageResponse() { Messages = new string[] { $"Failed to send to ChatScript: {ex.Message}" } }); } }
public void Init(out IEnumerator rcv) { handle = new TcpClientHandler(); handle.InitSocket(out rcv); id_mp = new Dictionary <ushort, Proto>(); ty_mp = new Dictionary <int, Proto>(); Regist(); }
public void Disconnect() { if (!IsConnected) { return; } m_client.Disconnect(); m_client = null; m_isLoggedIn = false; }
// Use this for initialization void Start() { //初始化网络连接 //tcpClient=new TcpClientHandler(); //因为tcp的类继承了monobehaviour所以不能用new,或者去掉对monobehaviour继承就可以用new tcpClient = gameObject.AddComponent <TcpClientHandler>(); tcpClient.InitSocket(); //找到cube cube = GameObject.Find("Cube"); }
public GameClient(TcpClientHandler tcpclient, int entityid, GameWorld gameWorld) { entityId = entityid; clientHandler = tcpclient; inputMap = new InputMap(); pingWatch = new Stopwatch(); priorityList = new List <int>(); updatedQueue = new Queue <int>(); updatePriorities(gameWorld.entityMap); }
/// <summary> /// Disconnect from current server /// </summary> public void Disconnect() { if (!IsConnected) { return; } IsConnected = false; m_client.Disconnect(); m_client = null; }
static void Main(string[] args) { TcpServer server = new TcpServer(); server.Run(); while (true) { System.Threading.Thread.Sleep(500); Console.Write("\n Your request:"); TcpClientHandler.ClientRequestString = Console.ReadLine(); TcpClientHandler.ConnectAsTcpClient("127.0.0.1", 1234); } }
void OnAccept(IAsyncResult ar) { Console.WriteLine("Client Connected"); TcpListener listener = (TcpListener)ar.AsyncState; TcpClient tcpClient = listener.EndAcceptTcpClient(ar); TcpClientHandler handler = new TcpClientHandler(tcpClient, session_id, this); if (connectedTcpClientPool.TryAdd(session_id, handler)) { session_id = Interlocked.Increment(ref session_id); } listener.BeginAcceptTcpClient(OnAccept, listener); }
public static async void SendAsync(TcpClientHandler client, BufferStream buffer) { if (client.Connected && client.Receiver.Connected) { try { client.Stream.Write(buffer.Memory, 0, buffer.Iterator); await client.Stream.FlushAsync(); } catch (System.IO.IOException e) { mainProgram.WriteLine(e.ToString()); } } }
public int createPlayer(GamePoint3D position, GamePoint2D size, TcpClientHandler client) { //this will ignore the max entity limit, however cannot ignore the max connection limit //returns if successful int i = 0; if (clientMap.Count < gameServer.MaxConnections) { while (entityMap.ContainsKey(i)) //looks to find the lowest open slot to make an entity { i += 1; } entityMap.Add(i, new GameEntity(position, size, i, this)); clientMap.Add(i, new GameClient(client, i, this)); } return(i); }
private static Task Main(/*string[] args*/) { Console.WriteLine("SocketServerApp is running..."); var hostName = Dns.GetHostName(); var socketConfiguration = new SocketConfiguration(hostName, 3333); var tcpListener = socketConfiguration.CreateTcpListener(); tcpListener.Start(); while (true) { var handler = tcpListener.AcceptTcpClient(); var clientHandler = new TcpClientHandler(handler); clientHandler.StartAsync(); } }
public bool Connect() { if (IsConnected) { Disconnect(); } m_client = new TcpClientHandler(m_ip, m_port); if (m_client.Connect()) { m_client.Disconnected += m_client_Disconnected; m_client.ReceivedFull += m_client_ReceivedFull; return true; } m_lastConnectionError = m_client.LastConnectError; m_client = null; return false; }
public bool Connect() { if (IsConnected) { Disconnect(); } m_client = new TcpClientHandler(m_ip, m_port); if (m_client.Connect()) { m_client.Disconnected += m_client_Disconnected; m_client.ReceivedFull += m_client_ReceivedFull; return(true); } m_lastConnectionError = m_client.LastConnectError; m_client = null; return(false); }
/// <summary> /// The constructor. /// </summary> /// <param name="server">The server.</param> /// <param name="client">The client.</param> public ChessServerPlayer(ChessServer server, TcpClientHandler client) { this.Actions = new Dictionary<string, Action<string>> { {"ListPlayers", ActionListPlayers}, {"Quit", ActionPlayerQuit}, {"Play", ActionPlay}, {"PlayOk", ActionPlayOk}, {"SetName", ActionSetName}, {"Game", ActionGame}, {"Send", ActionSend} }; this.Server = server; client.MessageReceived += MessageReceived; client.Disconnected += Disconnected; this.Client = client; this.Client.PingInterval = 2000; }
// Use this for initialization void Start() { //初始化网络连接 //tcpClient=new TcpClientHandler(); //因为tcp的类继承了monobehaviour所以不能用new,或者去掉对monobehaviour继承就可以用new tcpClient = gameObject.AddComponent <TcpClientHandler>(); tcpClient.InitSocket(); //btn1.onClick.AddListener(() => //{ // tcpClient.SocketSend("1"); // NodeCode.text = "节点编号:" + tcpClient.GetRecvStr(); //}); //btn2.onClick.AddListener(() => //{ // tcpClient.SocketSend("2"); // LightStrength.text = "当前光强:" + tcpClient.GetRecvStr(); //}); InvokeRepeating("init", 1, 10); }
/// <summary> /// The constructor. /// </summary> /// <param name="client">The client.</param> public ChessClientPlayer(TcpClientHandler client = null) { this.Actions = new Dictionary<string, Action<string>> { {"ListPlayers", ActionListPlayers}, {"Play", ActionPlay}, {"Send", ActionSend}, {"GameSend", ActionGameSend}, {"Moved", ActionMoved}, {"Welcome", ActionWelcome}, {"GameQuit", ActionGameQuit}, {"YourTurn", ActionYourTurn}, {"G2G", ActionG2G}, {"GameOver", ActionGameOver} //{"WTF", ActionWTF} }; this.InGame = false; this.Client = client; }
/// <summary> /// Connect to a server. If already connected to one, it will be disconnected to connect to the new one /// </summary> /// <returns>True if able to connect, or false if it didn't succeed</returns> public bool Connect() { if (m_ip == null) { throw new InvalidOperationException("Can not connect to a server if no Ip address is specified"); } if (IsConnected) { Disconnect(); } m_client = new TcpClientHandler(m_ip, m_port); if (m_client.Connect()) { m_client.Disconnected += m_client_Disconnected; m_client.ReceivedFull += m_client_ReceivedFull; return(true); } m_lastConnectionError = m_client.LastConnectError; m_client = null; return(false); }
public ActionResult OnPostSendMessageToChatScript(SendMessageRequest request) { var response = new SendMessageResponse(); try { var tcpClient = new TcpClient("localhost", 1024); using (ITcpClient client = new TcpClientHandler(tcpClient)) { var chatScript = new ChatScriptHandler(client); response = chatScript.SendMessage(request, _context); } } catch (Exception ex) { response.Messages = new string[] { ex.Message }; } string responseJson = JsonConvert.SerializeObject(response); return(Content(responseJson)); }
private static void event_connected(TcpClientHandler client) { mainProgram.WriteLine("Client connected from " + getIp(client).ToString()); //we'll put our code to initiate the player client here int entid_ = gameWorld.createPlayer(new GamePoint3D(0d, 0d, 512d), client); int sz_ = 16 + (gameWorld.entityMap.Count * 52) + (gameWorld.objectMap.Count * 52); BufferStream buff = new BufferStream(sz_, 1); buff.Write((ushort)3); buff.Write(entid_); buff.Write((uint)gameWorld.entityMap.Count); foreach (KeyValuePair <int, GameEntity> pair in gameWorld.entityMap) { buff.Write(pair.Value.id); buff.Write(pair.Value.pos.X); buff.Write(pair.Value.pos.Y); buff.Write(pair.Value.pos.Z); buff.Write(pair.Value.size.X); buff.Write(pair.Value.size.Y); buff.Write(pair.Value.direction); buff.Write(pair.Value.pitch); } buff.Write((uint)gameWorld.objectMap.Count); foreach (KeyValuePair <int, GameObject> pair in gameWorld.objectMap) { buff.Write(pair.Value.id); buff.Write(pair.Value.position.X); buff.Write(pair.Value.position.Y); buff.Write(pair.Value.position.Z); buff.Write(pair.Value.size.X); buff.Write(pair.Value.size.Y); buff.Write(pair.Value.size.Z); } gameWorld.sendToClient(client, buff); buff.Deallocate(); mainProgram.WriteLine("World and client data sent to socket " + client.Socket.ToString()); }
/// <summary> /// 启动Client连接 /// </summary> public void StartConnectServer() { IPEndPoint _remote=new IPEndPoint(IPAddress.Parse(strRemoteIP),nRemotePort); IPEndPoint _local=new IPEndPoint(IPAddress.Any,nLocalPort); NetTransCondiction ntc=new NetTransCondiction(); ntc.IsPackHead =true; ntc.IsShakeHand =true; tch = new TcpClientHandler(_local,_remote,ntc); tch.Connected += new System.EventHandler<NetEventArgs>(tsh_Connected); tch.DisConnected += new System.EventHandler<NetEventArgs>(tsh_DisConnected); tch.RecvMessage += new System.EventHandler<NetEventArgs>(tsh_RecvMessage); tch.SendMessage += new System.EventHandler<NetEventArgs>(tsh_SendMessage); tch._isPermitReconnect = true; try { tch.Connect(); } catch (Exception ex) { LOG.LogHelper.WriteLog("连接服务器异常", ex); } }
private static void event_clientOverflow(TcpClientHandler client) { mainProgram.WriteLine("Connection attempt from " + getIp(client).ToString() + ", socket " + client.Socket.ToString() + ", however the server is full"); }
public void Disconnect() { if (!IsConnected) return; m_client.Disconnect(); m_client = null; m_isLoggedIn = false; }
private void Disconnected(TcpClientHandler client) { this.ServerDisconnected.IfNotNull(a => a(this)); }
private void MessageReceived(TcpClientHandler client, string message) { try { Tuple<string, string> parts = ChessServer.GetParts(message); if (this.Actions.ContainsKey(parts.Item1)) { this.Actions[parts.Item1](parts.Item2); } } catch (ThreadAbortException) { } catch (Exception e) { this.ChatMessageReceived(this, "Exception: " + e.Message + Environment.NewLine + "Stack: " + e.StackTrace); } }
/// <summary> /// Handles receiving messages. /// </summary> /// <param name="client">The client sending the message.</param> /// <param name="message">The message.</param> private void MessageReceived(TcpClientHandler client, string message) { try { this.Server.Logger.LogIf(this.Server.Debug, "Received message: " + message); Tuple<string, string> parts = ChessServer.GetParts(message); if (this.Actions.ContainsKey(parts.Item1)) { this.Actions[parts.Item1](parts.Item2); } else { this.Client.SendMessage("WTF"); } } catch { } }
private static void event_attemptReconnect(TcpClientHandler client) { mainProgram.WriteLine("Client " + client.Socket.ToString() + "'s connection is unknown and unknowably unrecoverable (ip " + getIp(client).ToString() + ")"); //no code ahead because I have no idea how to reconnect a client }
/// <summary> /// A method that handles a disconnected client. /// </summary> /// <param name="client">The disconnecting client.</param> private void Disconnected(TcpClientHandler client) { string s; try { s = ": " + client.Client.Client.RemoteEndPoint.ToString(); } catch { s = "."; }; this.Server.Clients.Remove(this); this.Server.UpdateAllPlayerLists(); this.Client.Dispose(); this.Server.Logger.Log("Player disconnected" + s); }
/// <summary> /// A method that handles receiving messages. /// </summary> /// <param name="client">The client the message came from.</param> /// <param name="message">The message.</param> protected internal void ReceivedMessage(TcpClientHandler client, string message) { try { if (this.BlackPlayer.Client != client && this.WhitePlayer.Client != client) return; Tuple<string, string> parts = ChessServer.GetParts(message); if (this.Actions.ContainsKey(parts.Item1)) { this.Actions[parts.Item1](client, parts.Item2); } else { client.SendMessage("WTF"); } } catch { } }
/// <summary> /// The move action. /// </summary> /// <param name="client">The client that moved.</param> /// <param name="message">The move.</param> private void ActionMove(TcpClientHandler client, string message) { if ((this.Board.Turn == ChessColor.White && client == this.WhitePlayer.Client) || (this.Board.Turn == ChessColor.Black && client == this.BlackPlayer.Client)) { string[] sqs = message.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (this.Board[sqs[0]].To(this.Board[sqs[1]])) { this.Server.Logger.LogIf(this.Server.Debug, "Move: " + message + " (" + client.Client.Client.RemoteEndPoint.ToString() + ")"); this.SendMessageToAll("Moved " + sqs[0] + " " + sqs[1]); this.NextTurn(); } else { this.Server.Logger.LogIf(this.Server.Debug, "Invalid move: " + message + " (" + client.Client.Client.RemoteEndPoint.ToString() + ")"); client.SendMessage("YourTurn"); } } }
/// <summary> /// The send action. /// </summary> /// <param name="client">The client that sent the message.</param> /// <param name="message">The move.</param> private void ActionSend(TcpClientHandler client, string message) { string name = (client == this.BlackPlayer.Client ? this.BlackPlayer.Name : this.WhitePlayer.Name); this.SendMessageToAll("GameSend " + (name ?? client.Client.Client.RemoteEndPoint.ToString()) + ": " + message); }
/// <summary> /// A method that handles player disconnections. /// </summary> /// <param name="player">The player that disconnected.</param> private void PlayerDisconnected(TcpClientHandler player) { this.SendMessageToAll("GameQuit"); this.Dispose(); }
/// <summary> /// An event that is fired when a client is received. /// </summary> /// <param name="server">The server.</param> /// <param name="client">The client.</param> private void ClientReceived(TcpServer server, TcpClientHandler client) { this.Logger.Log("Client connected from " + client.Client.Client.RemoteEndPoint.ToString() + "."); this.Clients.Add(new ChessServerPlayer(this, client)); this.UpdateAllPlayerLists(); }
private void ServerDisconnectedHandler(TcpClientHandler client) { this.InGame = false; this.ChatMessageReceived.IfNotNull(a => a(this, "Server disconnected.")); this.ServerDisconnected.IfNotNull(a => a(this)); }