public Connect ( IPAddress address, int port ) : void | ||
address | IPAddress | |
port | int | |
return | void |
public void Start(string[] args) { registry = new Registry(); if (!registry.Register(this)) { Console.WriteLine("Error registering service."); return; } Console.WriteLine("Registered service."); try { TcpClient tcpclient = new TcpClient(); if (args.Count() != 2) throw new Exception("Argument must contain a publishing ip and port. call with: 127.0.0.1 12345"); tcpclient.Connect(args[0], Int32.Parse(args[1])); StreamReader sr = new StreamReader(tcpclient.GetStream()); string data; while ((data = sr.ReadLine()) != null) { Console.WriteLine("Raw data: " + data); if (RawAisData != null) RawAisData(data); } } catch (Exception e) { Console.WriteLine(e.Message + e.StackTrace); Console.WriteLine("Press enter"); Console.ReadLine(); } }
public void Connect() { if(_stream == null) { _client = new TcpClient(); if (_config.host != null) _client.Connect(_config.host, _config.port); else _client.Connect(new IPEndPoint(IPAddress.Parse(_config.ip), _config.port)); _stream = _client.GetStream(); } }
public Boolean Connect() { try { if (recvThread != null) recvThread.Abort(); } catch (Exception ex) { } tcpClient = new TcpClient(); try { tcpClient.Connect(ServerIP, Port); tcpClient.Client.Blocking = true; //tcpClient.Client.ReceiveTimeout = 1000; tcpClient.Client.LingerState = new LingerOption(true, 0); recvThread = new Thread(new ThreadStart(RecvRequestFromClient)); recvThread.Start(); IsConnected = true; return true; } catch (SocketException ex) { if (OnSocketError != null) OnSocketError(0, new SocketEventArgs((int)ex.ErrorCode, ex.Message)); } return false; }
private TcpClient ConnectRemote(IPEndPoint ipEndPoint) { TcpClient client = new TcpClient(); try { client.Connect(ipEndPoint); } catch (SocketException socketException) { if (socketException.SocketErrorCode == SocketError.ConnectionRefused) { throw new ProducerException("服务端拒绝连接", socketException.InnerException ?? socketException); } if (socketException.SocketErrorCode == SocketError.HostDown) { throw new ProducerException("订阅者服务端尚未启动", socketException.InnerException ?? socketException); } if (socketException.SocketErrorCode == SocketError.TimedOut) { throw new ProducerException("网络超时", socketException.InnerException ?? socketException); } throw new ProducerException("未知错误", socketException.InnerException ?? socketException); } catch (Exception e) { throw new ProducerException("未知错误", e.InnerException ?? e); } return client; }
/// <summary> /// Constructor /// </summary> public ListenerSocket() { // Init loadBalancerSocket = new TcpClient(); // Connect to the loadbalancer Console.Write("Enter the loadbalancer ip: "); // Prompt loadBalancerSocket.Connect(IPAddress.Parse(Console.ReadLine()), int.Parse(Server.Properties.Resources.LoadBalancerPort)); Logger.ShowMessage( String.Format("Connected to loadbalancer on: {0}:{1} and {2}:{3}", ((IPEndPoint)loadBalancerSocket.Client.LocalEndPoint).Address, ((IPEndPoint)loadBalancerSocket.Client.LocalEndPoint).Port, ((IPEndPoint)loadBalancerSocket.Client.RemoteEndPoint).Address, ((IPEndPoint)loadBalancerSocket.Client.RemoteEndPoint).Port ) ); Clients = new List<TcpClient>(); messageHandler = new MessageHandler(); // Make the socket listener and thread Random randomPort = new Random(); listenerSocket = new TcpListener(IPAddress.Any, randomPort.Next(8900, 9000)); listenThread = new Thread(new ThreadStart(ListenForClients)); listenThread.Start(); sendServerPort(loadBalancerSocket, ((IPEndPoint)listenerSocket.LocalEndpoint).Port); Logger.ShowMessage("Listener initialized."); Logger.ShowMessage("Listening on: " + ((IPEndPoint)listenerSocket.LocalEndpoint).Address + ":" + ((IPEndPoint)listenerSocket.LocalEndpoint).Port); // Define the handlers. PacketManager.DefineOpcodeHandlers(); }
public TestResultBase Test(Options o) { var p = new Uri(o.Url); var res = new GenericTestResult { ShortDescription = "TCP connection port " + p.Port, Status = TestResult.OK }; try { var client = new TcpClient(); client.Connect(p.DnsSafeHost, p.Port); res.Status = TestResult.OK; client.Close(); } catch (Exception ex) { res.Status = TestResult.FAIL; res.CauseOfFailure = ex.Message; } return res; }
static void Main(string[] args) { var port = Convert.ToInt32(args[0]); var timeout = Convert.ToInt32(args[1]); var buffer = new byte[12]; client = new TcpClient(); client.Connect(IPAddress.Loopback, port); client.Client.BeginReceive(termBuffer, 0, 1, SocketFlags.None, inputClient_DataReceived, null); Console.WriteLine("Connected to Nexus at 127.0.0.1:{0}", port); Wiimotes.ButtonClicked += Button; int numConnnected = Wiimotes.Connect(timeout); if (numConnnected > 0) { Console.WriteLine("{0} wiimote(s) found", numConnnected); CopyInt(ref buffer, 1, 0); CopyInt(ref buffer, numConnnected, 4); CopyInt(ref buffer, 0, 8); client.Client.Send(buffer); Wiimotes.Poll(); } else { CopyInt(ref buffer, 1, 0); CopyInt(ref buffer, 0, 4); CopyInt(ref buffer, 0, 8); client.Client.Send(buffer); Console.WriteLine("No Wiimotes found"); } }
public bool talk() { try { if (null != sendPro) { TcpClient client = new TcpClient(); client.Connect(IPAddress.Parse(ClientInfo.confMap.value(strClientConfKey.ServerIP)), int.Parse(ClientInfo.confMap.value(strClientConfKey.ServerPort))); NetworkStream ns = client.GetStream(); IFormatter formatter = new BinaryFormatter(); formatter.Serialize(ns, sendPro); reseivePro = (Protocol)formatter.Deserialize(ns); client.Close(); } else { return false; } return true; } catch (Exception) { return false; } }
public void ConnectToServer(string msg) { try { _client = new TcpClient(); _client.Connect(_endPoint); byte[] bytes = Encoding.ASCII.GetBytes(msg); using (NetworkStream ns = _client.GetStream()) { Trace.WriteLine("Sending message to server: " + msg); ns.Write(bytes, 0, bytes.Length); bytes = new byte[1024]; int bytesRead = ns.Read(bytes, 0, bytes.Length); string serverResponse = Encoding.ASCII.GetString(bytes, 0, bytesRead); Trace.WriteLine("Server said: " + serverResponse); } } catch (SocketException se) { Trace.WriteLine("There was an error talking to the server: " + se.ToString()); } finally { Dispose(); } }
public void StartClient() { TcpClient tc = new TcpClient(); tc.Connect("localhost", 9988); NetworkStream ns = tc.GetStream(); List<byte> dataList = new List<byte>(); //Node Id dataList.AddRange(BitConverter.GetBytes(1001)); //Node Name dataList.AddRange(Encoding.ASCII.GetBytes("NK1001")); //Temperature dataList.AddRange(BitConverter.GetBytes((short)37)); //Longitude dataList.AddRange(BitConverter.GetBytes((double)121.29)); dataList.Add(0); byte[] data = dataList.ToArray(); Console.WriteLine("Press <Enter> to send"); while (Console.ReadLine() != null) { ns.Write(data, 0, data.Length); } }
public Boolean Connect(String ip, int port) { try { TcpClient = new System.Net.Sockets.TcpClient(); TcpClient.ReceiveTimeout = 5000; TcpClient.SendTimeout = 5000; TcpClient.Connect(ip, port); Ns = TcpClient.GetStream(); Bw = new BinaryWriter(TcpClient.GetStream()); Br = new BinaryReader(TcpClient.GetStream()); IsConnected = true; } catch (Exception e) { IsConnected = false; Log.Cl(e.Message); return false; } ReceptionThread = new Thread(new ThreadStart(Run)); ReceptionThread.IsBackground = true; ReceptionThread.Start(); return true; }
public void Connect(string ip, int port = 8085) { _ip = ip; _port = port; _tcp = new TcpClient(); _tcp.Connect(_ip, _port); _ns = _tcp.GetStream(); ThreadPool.QueueUserWorkItem((x)=> { while(_tcp.Connected) { try { if (_ns.DataAvailable) { byte[] buffer = new byte[4096]; int bytesread = _ns.Read(buffer, 0, buffer.Length); Array.Resize(ref buffer, bytesread); string msg = Encoding.UTF8.GetString(buffer); HandlePacket(msg); } } catch { } } _ns.Close(); _ns.Dispose(); _tcp.Close(); Thread.CurrentThread.Abort(); }); }
private void Parse() { TcpClient tcpclient = new TcpClient(); // create an instance of TcpClient tcpclient.Connect("pop.mail.ru", 995); // HOST NAME POP SERVER and gmail uses port number 995 for POP System.Net.Security.SslStream sslstream = new SslStream(tcpclient.GetStream()); // This is Secure Stream // opened the connection between client and POP Server sslstream.AuthenticateAsClient("pop.mail.ru"); // authenticate as client //bool flag = sslstream.IsAuthenticated; // check flag System.IO.StreamWriter sw = new StreamWriter(sslstream); // Asssigned the writer to stream System.IO.StreamReader reader = new StreamReader(sslstream); // Assigned reader to stream sw.WriteLine("USER [email protected]"); // refer POP rfc command, there very few around 6-9 command sw.Flush(); // sent to server sw.WriteLine("PASS utybfkmyjcnm321"); sw.Flush(); sw.WriteLine("RETR 5"); sw.Flush(); sw.WriteLine("Quit "); // close the connection sw.Flush(); string str = string.Empty; string strTemp = string.Empty; while ((strTemp = reader.ReadLine()) != null) { if (".".Equals(strTemp)) { break; } if (strTemp.IndexOf("-ERR") != -1) { break; } str += strTemp; } MessageBox.Show(str); }
/// <summary> /// Connect TCP socket to a server. /// </summary> /// <param name="serverAddr">IP or hostname of server.</param> /// <param name="port">Port that TCP should use.</param> /// <returns>True if connection is successful otherwise false</returns> internal bool Connect(string serverAddr, int port) { try { IPAddress[] serverIP = Dns.GetHostAddresses(serverAddr); if (serverIP.Length <= 0) { mErrorString = "Error looking up host name"; return false; } mTCPClient = new TcpClient(); mTCPClient.Connect(serverIP[0], port); // Disable Nagle's algorithm mTCPClient.NoDelay = true; } catch (SocketException e) { mErrorString = e.Message; mErrorCode = e.SocketErrorCode; if (mTCPClient != null) { mTCPClient.Close(); } return false; } return true; }
private void Button3_Click(object sender, RoutedEventArgs e) { try { Assembly executingAssembly = Assembly.GetExecutingAssembly(); // load spim-generated data from embedded resource file const string spimDataName = "Simulation.Repressilator.txt"; using (Stream spimStream = executingAssembly.GetManifestResourceStream(spimDataName)) { using (StreamReader r = new StreamReader(spimStream)) { string line = r.ReadLine(); while (!r.EndOfStream) { TcpClient client = new TcpClient(); IPAddress ip1 = IPAddress.Parse(textBox1.Text.Trim());//{ 111, 186, 100, 46 } client.Connect(ip1, 8500); Stream streamToServer = client.GetStream(); // 获取连接至远程的流 line = r.ReadLine(); byte[] buffer = Encoding.Unicode.GetBytes(line); streamToServer.Write(buffer, 0, buffer.Length); streamToServer.Flush(); streamToServer.Close(); client.Close(); Thread.Sleep(10); // Long-long time for computations... } } } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
static void client() { var s = new TcpClient(); s.Connect("www.technikum-wien.at", 80); var stream = s.GetStream(); StreamWriter sw = new StreamWriter(stream); sw.WriteLine("GET / HTTP/1.1"); sw.WriteLine("host: www.technikum-wien.at"); sw.WriteLine("connection: close"); sw.WriteLine(); sw.Flush(); // Shift+Alt+F10 StreamReader sr = new StreamReader(stream); while (!sr.EndOfStream) { var line = sr.ReadLine(); Console.WriteLine(line); } Console.ReadKey(); }
private void sendButton_Click(object sender, EventArgs e) { BulletinMessage msg = new BulletinMessage(); msg.Content = this.messageBox.Text; msg.Timestamp = DateTime.Now; this.statusLogBox.AppendText("CLIENT: Opening connection" + Environment.NewLine); using (TcpClient client = new TcpClient()) { client.Connect(IPAddress.Loopback, 8888); using (NetworkStream stream = client.GetStream()) { this.statusLogBox.AppendText("CLIENT: Got connection; sending message..." + Environment.NewLine); this.statusLogBox.AppendText(msg.ToString() + Environment.NewLine); // send data to server Serializer.SerializeWithLengthPrefix(stream, msg, PrefixStyle.Base128); this.statusLogBox.AppendText("CLIENT: Closing connection" + Environment.NewLine); stream.Close(); } client.Close(); } }
/// <summary> /// Creates a communication channel using ServerIpAddress and ServerPort. /// </summary> /// <returns>Ready communication channel to communicate</returns> protected override ICommunicationChannel CreateCommunicationChannel() { TcpClient client = new TcpClient(); SslStream sslStream; var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { client = new TcpClient(); client.Connect(new IPEndPoint(IPAddress.Parse(_serverEndPoint.IpAddress), _serverEndPoint.TcpPort)); sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateCertificate), new LocalCertificateSelectionCallback(SelectLocalCertificate)); X509Certificate2Collection clientCertificates = new X509Certificate2Collection(); if (_clientCert != null) { clientCertificates.Add(_clientCert); } sslStream.AuthenticateAsClient(_nombreServerCert, clientCertificates, SslProtocols.Default, false); return new TcpSslCommunicationChannel( _serverEndPoint, client, sslStream); } catch (AuthenticationException) { client.Close(); throw; } }
public void Invoke() { var uri = this.Target; var t = new TcpClient(); t.Connect(uri.Host, this.Port); //var w = new StreamWriter(t.GetStream()); var w = new StringBuilder(); w.AppendLine("GET" + " " + uri.PathAndQuery + " HTTP/1.1"); w.AppendLine("Host: " + uri.Host); w.AppendLine("Connection: Close"); // http://www.botsvsbrowsers.com/ w.Append(@"User-Agent: jsc Referer: " + this.Referer + @" Accept: */* Accept-Encoding: gzip,deflate Accept-Language: et-EE,et;q=0.8,en-US;q=0.6,en;q=0.4 Accept-Charset: windows-1257,utf-8;q=0.7,*;q=0.3 "); w.AppendLine(); var data = Encoding.UTF8.GetBytes(w.ToString()); t.GetStream().Write(data, 0, data.Length); // it will take up to a minute to show up t.Close(); }
public void StartListen_then_StopListen_could_not_be_able_to_connect() { var testPort = GetTestPort(); using (var portListener = new PortListener(IPAddress.Loopback, testPort)) { portListener.StartListen(); portListener.StopListen(); var task = Task<bool>.Factory.StartNew(() => { using (var client = new TcpClient()) { try { client.Connect(IPAddress.Loopback.ToString(), testPort); } catch (Exception) { return false; } return true; } }, TaskCreationOptions.LongRunning); if (task.Wait(200)) { Assert.False(task.Result); } } }
static bool ReportError(string log, string stacktrace) { try { TcpClient client = new TcpClient(); //IPAddress addr = IPAddress.Parse("fonline2238.net"); IPAddress addr = IPAddress.Parse("127.0.0.1"); client.Connect(addr, 2250); NetworkStream stream = client.GetStream(); IPHostEntry IPHost = Dns.GetHostEntry(Dns.GetHostName()); string localip=IPHost.AddressList[0].ToString(); Byte[] data = System.Text.Encoding.ASCII.GetBytes("edata|||"+localip+"|||"+log+"|||"+stacktrace); stream.Write(data, 0, data.Length); // Receive the TcpServer.response. // Close everything. stream.Close(); client.Close(); } catch (ArgumentNullException) { return false; } catch (SocketException) { return false; } return true; }
static void Main(string[] args) { TcpClient clientSocket = new TcpClient(); clientSocket.Connect("localhost", 8888); NetworkStream serverStream = clientSocket.GetStream(); byte[] inStream = new byte[10025]; byte[] outStream; while (true) { serverStream.Read(inStream, 0, (int)clientSocket.ReceiveBufferSize); string s = SocketHelper.getString(inStream); s = s.Substring(0, s.IndexOf('\0')); int t = 0; Int32.TryParse(s, out t); s = (t + 1).ToString(); Console.WriteLine(s); outStream = SocketHelper.getBytes(s); serverStream.Write(outStream, 0, outStream.Length); serverStream.Flush(); } //byte[] outStream = Encoding.ASCII.GetBytes(Console.ReadLine()); //serverStream.Write(outStream, 0, outStream.Length); //serverStream.Flush(); Console.ReadLine(); }
static void RunClient(object state) { Customer cust = Customer.Invent(); Console.WriteLine("CLIENT: Opening connection..."); using (TcpClient client = new TcpClient()) { client.Connect(new IPEndPoint(IPAddress.Loopback, PORT)); using (NetworkStream stream = client.GetStream()) { Console.WriteLine("CLIENT: Got connection; sending data..."); Serializer.SerializeWithLengthPrefix(stream, cust, PrefixStyle.Base128); Console.WriteLine("CLIENT: Attempting to read data..."); Customer newCust = Serializer.DeserializeWithLengthPrefix<Customer>(stream, PrefixStyle.Base128); Console.WriteLine("CLIENT: Got customer:"); newCust.ShowCustomer(); Console.WriteLine("CLIENT: Sending happy..."); stream.WriteByte(123); // just to show all bidirectional comms are OK Console.WriteLine("CLIENT: Closing..."); stream.Close(); } client.Close(); } }
public static string ListFiles() { using (TcpClient socket = new TcpClient()) { string total = null; socket.Connect(IPAddress.Loopback, PORT); StreamWriter output = new StreamWriter(socket.GetStream()); // Send request type line output.WriteLine("LIST_FILES"); // Send message end mark and flush it output.WriteLine(); output.Flush(); // Read response string line; StreamReader input = new StreamReader(socket.GetStream()); while ((line = input.ReadLine()) != null && line != string.Empty) total += line + "/n"; output.Close(); socket.Close(); return total; } }
public void TestListen() { try { Identd.Start("username"); Thread.Sleep( 1000 ); TcpClient client = new TcpClient(); client.Connect("localhost", 113); StreamWriter writer = new StreamWriter( client.GetStream() ); writer.WriteLine( "a query" ); writer.Flush(); StreamReader reader = new StreamReader( client.GetStream() ); string line = reader.ReadLine(); Identd.Stop(); Assertion.AssertEquals( "a query : USERID : UNIX : username", line.Trim() ); } catch( Exception e ) { Assertion.Fail("IO Exception during test:" + e); } }
public void createClient(short portNumber) { ClientInit init = new ClientInit(); init.newClientInit(); mainClient = new TcpClient(); mainClient.Connect(init.hostAddr , portNumber); NetworkStream nStream = mainClient.GetStream(); usrData.userID = init.serverHandshake(nStream, encoding); mThread = new Thread(messageThread); mThread.Start(nStream); byte[] buffer; string message; Console.SetCursorPosition(0, 21); while ((message = Console.ReadLine()) != "!exit") { buffer = encoding.GetBytes(message); nStream.Write(buffer, 0, message.Length); nStream.Flush(); updateMessages(string.Format("me: {0}", message)); message = ""; clearConsoleLines(1, 21); Console.SetCursorPosition(0, 21); } mThread.Abort(); mainClient.Close(); }
public void Connect(IPEndPoint remoteAddress) { BaseSocket = new TcpClient(); BaseSocket.Connect(remoteAddress); OutputStream = new StreamWriter(new BufferedStream(BaseSocket.GetStream())); InputStream = new StreamReader(new BufferedStream(BaseSocket.GetStream())); }
public void WorkerProcessMain(string argument, string passwordBase64) { int port = int.Parse(argument, CultureInfo.InvariantCulture); client = new TcpClient(); client.Connect(new IPEndPoint(IPAddress.Loopback, port)); Stream stream = client.GetStream(); receiver = new PacketReceiver(); sender = new PacketSender(stream); shutdownEvent = new ManualResetEvent(false); receiver.ConnectionLost += OnConnectionLost; receiver.PacketReceived += OnPacketReceived; sender.WriteFailed += OnConnectionLost; // send password sender.Send(Convert.FromBase64String(passwordBase64)); receiver.StartReceive(stream); while (!shutdownEvent.WaitOne(SendKeepAliveInterval, false)) { Program.Log("Sending keep-alive packet"); sender.Send(new byte[0]); } Program.Log("Closing client (end of WorkerProcessMain)"); client.Close(); shutdownEvent.Close(); }
private static void ListLocations(string fileName) { using (TcpClient socket = new TcpClient()) { socket.Connect(IPAddress.Loopback, PORT); StreamWriter output = new StreamWriter(socket.GetStream()); // Send request type line output.WriteLine("LIST_LOCATIONS"); // Send message payload output.WriteLine(fileName); // Send message end mark and flush it output.WriteLine(); output.Flush(); // Read response string line; StreamReader input = new StreamReader(socket.GetStream()); while ((line = input.ReadLine()) != null && line != string.Empty) Console.WriteLine(line); output.Close(); socket.Close(); } }
/// <summary> /// Initializes a new instance of the <see cref="Alaris.Core.ClientListener"/> class. /// </summary> /// <param name='port'> /// Port to listen on. /// </param> public ClientSocket(string host, int port, string password) { _password = password; client = new TcpClient(); client.Connect(host, port); sClientPacketHandler.Init(); }