public static void Main(string[] args) { object tLck = new object(); var tCount = 0; int lastSended = 0, lastRec = 0; while (true) { if (tCount < 1) { var action = new Action(() => { var client = new TcpClientSocket(); // client.HandleMessage += Client_HandleMessage; if (client.Connect("10.202.196.51", 23456)) { lock (tLck) tCount++; Message msg = new Message(); //client.SendMessageAsync(msg); var loop = 100000000; Thread.Sleep(1000); while (loop-- > 0) { // Thread.Sleep(300); // if (sendCount % 2 == 0) { msg.Value = $"{sendCount}Client: SendMessgae:{DateTime.Now}"; //client.SendMessage(msg, 10000); } // else { msg.Value = $"{sendCount}Client: SendMessgaeSync:{DateTime.Now}"; if (client.SendMessageAsync(msg)) { lock (lck2) sendCount++; } else { lock (tLck) tCount--; break; } } } } client.Dispose(); }); Task task = new Task(action); task.Start(); } Console.WriteLine($"发出:{sendCount} 收到:{recCount} 线程数:{tCount}"); Console.Title = $"发出:{sendCount - lastSended} 接收:{recCount - lastRec} 线程数:{tCount}"; lastSended = sendCount; lastRec = recCount; //sendCount = 0; Thread.Sleep(1000); } }
public void OnMessage(TcpClientSocket tcpsocket, byte[] data, int size) { //Console.WriteLine("OnMessage dosomething"); // call SprotoRpc.Dispatch to unpack sproto package RpcMessage message = Proto.UnpackMessage(data, size); Console.WriteLine("[{0}] op=OnMessage,proto={1},tag={2},ud={3},session={4},type={5},request={6},response={7}", tcpsocket.Name, message.proto, message.tag, message.ud, message.session, message.type, message.request, message.response); }
private void OnDisconnected(object sender, EventArgs eventArgs) { UpdateRunner.RemoveUpdate(this); Status = ClientNetworkStatus.Disconnected; m_ClientSocket.OnConnect -= OnConnected; m_ClientSocket.OnReceive -= OnReceived; m_ClientSocket.OnDisconnect -= OnDisconnected; m_ClientSocket = null; }
public void Connect(IPAddress ip, int port) { TcpClientSocket tcpClientSocket = new TcpClientSocket(); this.socket = tcpClientSocket; tcpClientSocket.OnConnected += delegate(TcpClientSocket sender) { this.onConnected(); }; tcpClientSocket.Connect(ip, port); }
private void SendHandshake(TcpClientSocket socket) { var handshake = new MessageStream(1, 5 * sizeof(uint)); handshake.Write(ServiceHost.Instance.ProtocolVersion); handshake.Write(ServiceHost.Instance.HostGuid); handshake.Write(ServiceGuid); handshake.Write(ServiceUid); handshake.Write(InterfaceUids); socket.Post(handshake); }
public static void GenerateExternal() { Debug.Log("Connecting..."); var client = new TcpClientSocket(); client.OnConnect += onConnected; client.OnReceive += onReceive; client.OnDisconnect += onDisconnect; client.Connect(IPAddress.Parse("127.0.0.1"), 3333); AssetDatabase.Refresh(); }
public Connection(ServiceBase service, TcpClientSocket socket) { Service = service; Socket = socket; if (socket != null) { ChannelId = socket.ChannelId; } else { ChannelId = 0; } }
/// <summary> /// 建立Tcp鏈接 Start and connect remote service. /// </summary> /// <param name="IpAddr">connect server ip address.</param> /// <param name="Port">entry prot number.</param> /// <returns>System.Boolean</returns> public bool Connect(IPAddress IpAddr, ushort Port) { // create scan server port class object .. ScanPort Ping = new ScanPort(); // ping renbar server can connect .. if (Ping.Scan(IpAddr, Port)) { // connecting renbar center server .. ClientRequest = new TcpClientSocket(IpAddr, Port); } else { return(false); } return(true); }
bool isSocketReady() { if (this.socket != null) { TcpServerSocket tcpServerSocket = this.socket as TcpServerSocket; if (tcpServerSocket != null) { return(tcpServerSocket.count > 0); } TcpClientSocket tcpClientSocket = this.socket as TcpClientSocket; if (tcpClientSocket != null) { return(tcpClientSocket.isConnected); } } return(false); }
static void initClient(string[] args) { IPAddress ip = null; int port = 0; try { ip = IPAddress.Parse(args[1]); port = int.Parse(args[2]); var client = new TcpClientSocket(); client.OnDisconnect += onDisconnect; client.Connect(ip, port); _socket = client; start(); } catch (Exception) { Console.WriteLine("Please specify a valid ip and port"); } }
private void beginReceiving(TcpClientSocket client) { client.DataReceived += (ds, de) => { string payloadString = Encoding.ASCII.GetString(de.Payload); // If the message starts with a special string, update the username if (payloadString.StartsWith("<c>username")) { client.Username = payloadString.Remove(0, 11); this.Invoke((MethodInvoker)(() => clbConnectedClients.Items.Add($"{client.Username}"))); AppendText($"{client.Username} has connected. ({client.GetIpEndPointString()})"); } else { TotalMessagesRecieved++; AppendText($"{client.Username}: {Encoding.ASCII.GetString(de.Payload)}"); TsslReceivedMessages.Text = $"Received Messages: {TotalMessagesRecieved}"; } }; client.Disconnected += (ds, de) => { try { // Output to the server console AppendText($"{client.Username} has disconnected!"); // Remove the socket from the checked list box clbConnectedClients.InvokeIfRequired(s => { s.Items.RemoveAt(this.serverSocket.GetClientListIndex(client)); }); // Remove the socket from the list of connected clients. this.serverSocket.ConnectedClients.Remove(client); // Displays how many clients are connected TsslConnectedClients.Text = $"Connected Clients: {this.serverSocket.ConnectedClients.Count}"; } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }; }
// 開始処理 private void Form_Load(object sender, EventArgs e) { // フォームのLoadイベントで開始処理を呼ぶ tcpClientToolStrip.Begin(@"SETTING.INI", this.Text); //tcpClientToolStrip.Socket.FixedLocalPort = 4567; // ソケット socket = tcpClientToolStrip.Socket; // パケット数カウンタ表示 updateCounter(); // 対話通信スレッド開始 threadInterCommQuit = false; threadInterComm = new Thread(new ThreadStart(() => { threadInterCommFunc(); })); threadInterComm.Start(); }
public bool Connect(string ipString, int port) { if (m_ClientSocket != null) { return(false); } m_ClientSocket = new TcpClientSocket(); m_ClientSocket.OnConnect += OnConnected; m_ClientSocket.OnReceive += OnReceived; m_ClientSocket.OnDisconnect += OnDisconnected; Status = ClientNetworkStatus.Connecting; m_ClientSocket.Connect(IPAddress.Parse(ipString), port); UpdateRunner.AddUpdate(this); return(true); }
private void Send(TcpClientSocket _tcpSocket, string _sendMessage) { if (_tcpSocket != null && _tcpSocket.Connected) { if (_sendMessage.ToLower() != "disconnect") { byte[] msgPayload = Encoding.ASCII.GetBytes(_sendMessage); _tcpSocket.SendAsync(msgPayload); } else { _tcpSocket.Disconnect(); return; } } else { return; } }
public TestTcpClientSocket() { string c2s = @" .package { type 0 : integer session 1 : integer ud 2 : integer } C2GS_Ping 1006 { request { str 0 : string } } "; string s2c = @" .package { type 0 : integer session 1 : integer ud 2 : integer } GS2C_Pong 1108 { request { str 0 : string time 1 : integer } } "; SprotoMgr C2SProto = SprotoParser.Parse(c2s); SprotoMgr S2CProto = SprotoParser.Parse(s2c); Proto = new SprotoRpc(S2CProto, C2SProto); TcpSocket = new TcpClientSocket(); }
protected override void run() { var port = 0; try { port = int.Parse(_rawArgs[1]); _command = string.Join(" ", _rawArgs.Skip(2).ToArray()); } catch (Exception) { port = 3333; _command = string.Join(" ", _rawArgs.Skip(1).ToArray()); } var client = new TcpClientSocket(); client.OnConnect += onConnected; client.OnReceive += onReceive; client.OnDisconnect += onDisconnect; client.Connect(IPAddress.Parse("127.0.0.1"), port); while (true) { } }
public override void Run(string[] args) { var port = 0; try { port = int.Parse(args[1]); _command = args[2]; } catch (Exception) { port = 3333; _command = args[1]; } var client = new TcpClientSocket(); client.OnConnect += onConnected; client.OnReceive += onReceive; client.OnDisconnect += onDisconnect; client.Connect(IPAddress.Parse("127.0.0.1"), port); while (true) { } }
private void TestInternal(string host, int port) { var client = new TcpClientSocket(); client.Resolve(host, port.ToString(), (args1) => { if (!args1.Successful) { Console.WriteLine("failed to resolve host {0}", host); return; } Console.WriteLine("host resolved to {0}", args1.Data); client.Connect(args1.Data[0], (args2) => { if (!args2.Successful) { Console.WriteLine("connection failed"); return; } Console.WriteLine("connection to {0} successful", args1.Data); client.Close(false, (args3) => { if (!args3.Successful) { Console.WriteLine("failed to close connection"); return; } Console.WriteLine("connection closed"); }); }); }); }
// Start receiving messages from the server. // Handles client disconnection from the server. private void beginReceiving(TcpClientSocket client) { client.DataReceived += (ds, de) => { string receivedMessage = Encoding.ASCII.GetString(de.Payload); if (!RunCommand(receivedMessage, true)) { if (client.GetIpEndPointString().Contains("25565")) { RichTextBoxExtensions.AppendText(rtbClientMessages, $"\nServer: {Encoding.ASCII.GetString(de.Payload)}", Color.Blue); } else { AppendText($"{client.GetIpEndPointString()}: {Encoding.ASCII.GetString(de.Payload)}"); } } }; client.Disconnected += (ds, de) => { DisconnectFromServer(); }; }
static void Client_HandleMessage(TcpClientSocket sender, Message msg) { lock (lck) recCount++; //Console.WriteLine($"收到的信息为:{msg.Value}"); }
public string Start(string hostName, int portNum, bool autoReconnect = true) { _hostName = hostName; _port = portNum; _autoReconnect = autoReconnect; _client = new TcpClientSocket(AddressFamily.InterNetwork); _sessionId = Guid.NewGuid().ToString(); Connect(); return _sessionId; }
/// <summary> /// This method gets called by the ServiceHost each time a service provider /// with a matching serviceTypeId was found. Naturally this gets only called /// for service clients. /// </summary> /// <param name="remoteHostGuid"></param> /// <param name="serviceGuid"></param> /// <param name="serviceTag"></param> /// <param name="remoteEndPoint"></param> internal bool AddProvider(ulong remoteHostGuid, ulong remoteServiceGuid, ulong remoteInterfaceUids, ushort serviceTag, IPEndPoint remoteEndPoint) { if (IsProvider) { throw new InvalidOperationException(); } lock (_knownRemoteServiceGuids) { // Swap the two interface uids to ease comparison with the // local uids. remoteInterfaceUids = (remoteInterfaceUids << 32) | (remoteInterfaceUids >> 32); if (_knownRemoteServiceGuids.Contains(remoteServiceGuid)) { return(false); } _knownRemoteServiceGuids.Add(remoteServiceGuid); if (remoteInterfaceUids != InterfaceUids) { var foundIncompatibleRemoteService = FoundIncompatibleRemoteService; if (foundIncompatibleRemoteService != null) { var e = new FoundIncompatibleRemoteServiceArgs( remoteHostGuid, ServiceGuid, remoteServiceGuid, ServiceUid, InterfaceUids, remoteInterfaceUids, remoteEndPoint); foundIncompatibleRemoteService(this, e); } return(false); } lock (_connections) { foreach (var connection in _connections) { if (connection.Value.ServiceGuid == remoteServiceGuid) { throw new InvalidOperationException(); } } bool accept = true; var foundRemoteService = FoundRemoteService; if (foundRemoteService != null) { var e = new FoundRemoteServiceArgs(remoteHostGuid, remoteServiceGuid, serviceTag, remoteEndPoint); foundRemoteService(this, e); accept = e.Accept; } if (!accept) { return(false); } var socket = new TcpClientSocket(); socket.ConnectFailed += OnConnectFailed; socket.Connected += OnConnected; socket.Disconnected += OnDisconnected; socket.Connect(remoteEndPoint); return(true); } } }
/// <summary> /// Connects to the server and sends the username. /// </summary> /// <param name="userName"> The client's username for the chat. </param> void ConnectToServer(string userName) { if (!string.IsNullOrWhiteSpace(userName)) { socket = new TcpClientSocket(); socket.AsyncConnectionResult += (s, e) => { // If connected to the server if (e.Connected) { // Send the username to the server. byte[] msgPayload = Encoding.ASCII.GetBytes("<c>username" + userName); socket.SendAsync(msgPayload); // Start receiving messages from the server. beginReceiving(socket); rtbClientMessages.InvokeIfRequired(s1 => { // Displays that a client has connected if (s1.Text.Length <= 0) { this.Invoke((MethodInvoker)(() => rtbClientMessages.AppendText("Connected to the server."))); } else { this.Invoke((MethodInvoker)(() => rtbClientMessages.AppendText("\nConnected to the server."))); } }); btnConnect.InvokeIfRequired(bc => { bc.Text = "Connected"; }); btnSend.InvokeIfRequired(bs => { bs.Enabled = true; }); } else { ConnectToServer(userName); } }; try { // Set the connection controls to disabled btnConnect.Text = "Connecting"; btnConnect.Enabled = false; tbUsername.Enabled = false; // Connect to the server. socket.ConnectAsync(ipEnd); } catch (Exception ex) { // Set the conncet controls to enabled btnConnect.Text = "Connect"; btnConnect.Enabled = true; tbUsername.Enabled = true; MessageBox.Show(ex.ToString(), "Cannot Connect To Server"); } } else { MessageBox.Show("Please enter a valid username.", "Invalid Username"); } }
void when_created() { TcpClientSocket client = null; before = () => { client = new TcpClientSocket(); }; it["isn't connected"] = () => client.isConnected.should_be_false(); it["disconnects without triggering event"] = () => { client.OnDisconnect += (sender, e) => fail(); client.Disconnect(); }; it["can not connect when host is not available"] = () => { client.OnConnect += (sender, e) => fail(); client.Connect(IPAddress.Loopback, Port); wait(); client.isConnected.should_be_false(); }; it["can connect when host is available"] = () => { var didConnect = false; createServer(Port); client.OnConnect += (sender, e) => didConnect = true; client.Connect(IPAddress.Loopback, Port); wait(); client.isConnected.should_be_true(); didConnect.should_be_true(); closeServer(); }; it["can't send"] = () => client.Send(new byte[] { 1, 2 }); context["when connected"] = () => { before = () => { createServer(Port); client.Connect(IPAddress.Loopback, Port); wait(); }; after = () => { closeServer(); }; it["can disconnect"] = () => { var didDisconnect = false; client.OnDisconnect += (sender, e) => didDisconnect = true; client.Disconnect(); wait(); client.isConnected.should_be_false(); didDisconnect.should_be_true(); }; it["receives disconnect"] = () => { var didDisConnect = false; client.OnDisconnect += (sender, e) => didDisConnect = true; closeServer(); wait(); didDisConnect.should_be_true(); client.isConnected.should_be_false(); }; it["receives message"] = () => { const string message = "Hello"; var receivedMessage = string.Empty; client.OnReceive += (sender, e) => receivedMessage = Encoding.UTF8.GetString(e.bytes); _clientServer.Send(Encoding.UTF8.GetBytes(message)); wait(); message.should_be(receivedMessage); }; it["receives multiple messages"] = () => { const string message1 = "Hello1"; const string message2 = "Hello2"; ReceiveEventArgs receiveEventArgs = null; client.OnReceive += (sender, e) => receiveEventArgs = e; _clientServer.Send(Encoding.UTF8.GetBytes(message1)); wait(); message1.should_be(Encoding.UTF8.GetString(receiveEventArgs.bytes)); _clientServer.Send(Encoding.UTF8.GetBytes(message2)); wait(); message2.should_be(Encoding.UTF8.GetString(receiveEventArgs.bytes)); }; it["can send"] = () => { const string message = "Hello"; var receivedMessage = string.Empty; byte[] buffer = new byte[_clientServer.ReceiveBufferSize]; _clientServer.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, ar => { var server = (Socket)ar.AsyncState; var bytesReceived = server.EndReceive(ar); var trimmedBuffer = new byte[bytesReceived]; Array.Copy(buffer, trimmedBuffer, bytesReceived); receivedMessage = Encoding.UTF8.GetString(trimmedBuffer); }, _clientServer); client.Send(Encoding.UTF8.GetBytes(message)); wait(); message.should_be(receivedMessage); }; }; }
public NetworkStream(TcpClientSocket sock) { _tcpClientSocket = sock; }
void onConnected(TcpClientSocket client) { client.Send(Encoding.UTF8.GetBytes(_command)); }
static void onConnected(TcpClientSocket client) { Debug.Log("Connected."); Debug.Log("Generating..."); client.Send(Encoding.UTF8.GetBytes("gen")); }
public void TcpTest() { object monitor = new object(); lock (monitor) { bool clientMaySend = false; int payloadCounter = 0; Console.WriteLine("Starting server"); HashSet <Socket> connectedSockets = new HashSet <Socket>(); TcpServerSocket server = null; server = new TcpServerSocket(socket => { lock (monitor) { lock (connectedSockets) { Console.WriteLine("Server received client's connection"); connectedSockets.Add(socket); } } }, (sender, buffer, size) => { lock (monitor) { Console.WriteLine("SRec " + size); server.Send(sender, buffer, 0, size); } }, socket => { lock (connectedSockets) { Console.WriteLine("Server lost connection to client"); connectedSockets.Remove(socket); } }, connectedSockets, 1, Port); byte[] sendBuffer = new byte[DataSize]; _random.NextBytes(sendBuffer); Console.WriteLine("Starting client"); TcpClientSocket client = null; client = new TcpClientSocket(() => { lock (monitor) { Console.WriteLine("Client connected to server"); if (clientMaySend) { Console.WriteLine("Client not waiting for main thread"); } else { Console.WriteLine("Client waiting for main thread"); Monitor.Wait(monitor); } Console.WriteLine("Client sending first data"); client.Send(sendBuffer, 0, sendBuffer.Length); } }, error => { lock (monitor) { Console.WriteLine("Client failed to connect to server: " + error); } }, (buffer, size) => { lock (monitor) { Console.WriteLine("CRec " + size); AssertArrayContentsEqualInFirstArrayLengthRange(sendBuffer, buffer); if (++payloadCounter == PayloadCount) { Monitor.Pulse(monitor); } else { _random.NextBytes(sendBuffer); client.Send(sendBuffer, 0, sendBuffer.Length); } } }, () => Console.WriteLine("Client lost connection to server")); client.Start(Ip, Port); clientMaySend = true; Monitor.Pulse(monitor); Console.WriteLine("Main thread waiting"); Monitor.Wait(monitor); Console.WriteLine("Closing client"); client.Close(); Console.WriteLine("Closing server"); server.Close(); } }
public void OnClose(TcpClientSocket tcpsocket) { //Console.WriteLine("OnClose dosomething"); }
/// <summary> /// Constructor for a new Client /// </summary> /// <param name="tcpClient">The TCP client</param> /// <param name="buffer">The byte array buffer</param> public Client(TcpClientSocket tcpClient, byte[] buffer) { tcpClient.ReceiveBufferSize = 65535; if (tcpClient == null) throw new ArgumentNullException("tcpClient"); if (buffer == null) throw new ArgumentNullException("buffer"); this.TcpClient = tcpClient; this.Buffer = buffer; this.SessionId = Guid.NewGuid().ToString(); }