public Connect ( |
||
remoteEP | ||
Résultat | void |
public void ConnectHost(string host, int port) { _tcpSock.Connect(host, port); if (_tcpSock.Connected) { if (ClientConnected != null) { ClientConnected(this, null); } } }
private static void RunMain(CommandLineArguments args) { var packet = Network.Package.Power + Encoding.Default.GetBytes(args.LiveId).ToHexString() + "00"; var ascii = packet.ToAsciiString(); Console.WriteLine(Message.SendPackage, args.Address); try { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.IP) { Blocking = false }) { socket.Connect(args.Address, Network.Port); for (var i = 0; i < 5; i++) { socket.Send(Encoding.Default.GetBytes(ascii)); Thread.Sleep(1000); } socket.Close(); } Console.WriteLine(Message.Finish); } catch (Exception ex) { Console.WriteLine(Message.Error, ex.Message); } }
private void createSockets() { IPAddress tmp_addr = null; tmp_addr = Address.Resolve(Enclosing_Instance.discovery_addr); mcast_addr = new Address(tmp_addr, Enclosing_Instance.discovery_port); try { IPEndPoint sendEndPoint = new IPEndPoint(mcast_addr.IpAddress, mcast_addr.Port); IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 0); mcast_send_sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); mcast_send_sock.Bind(localEndPoint); mcast_send_sock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(mcast_addr.IpAddress, IPAddress.Any)); mcast_send_sock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, ip_ttl); mcast_send_sock.Connect(sendEndPoint); } catch (Exception ex) { throw ex; } setBufferSizes(); }
public static void WakeUp(byte[] mac) { using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { IPEndPoint endPoint = new IPEndPoint(new IPAddress(4294967295), 40000); // IP 255.255.255.255 socket.Connect(endPoint); byte[] packet = new byte[17 * 6]; for (int i = 0; i < 6; i++) { packet[i] = 0xFF; } for (int i = 1; i <= 16; i++) { for (int j = 0; j < 6; j++) { packet[i * 6 + j] = mac[j]; } } socket.Send(packet); // , SocketFlags.Broadcast); } }
private void OnFileTransferStateChanged(FileTransferState state, FileTransferStateChangeReason reason) { Console.WriteLine(MSG_PREFIX + "OnFileTransferStateChanged: state {0}, reason {1}", state.ToString(), reason.ToString()); switch (state) { case FileTransferState.Open: s = new System.Net.Sockets.Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP); EndPoint ep = new UnixEndPoint(socket_addr); s.Connect(ep); if (transfer_initiator == self_handle) { Console.WriteLine(MSG_PREFIX + "Sending file"); ThreadPool.QueueUserWorkItem(delegate { SendFile(); }); } else { Console.WriteLine(MSG_PREFIX + "Receiving file"); ThreadPool.QueueUserWorkItem(delegate { ReceiveFile(); }); } break; case FileTransferState.Completed: Console.WriteLine(MSG_PREFIX + "Transfer completed."); ift.Close(); break; } }
public void SendMessage(string msg) { var clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); clientSocket.Connect(Host, Port); clientSocket.Send(Encoding.ASCII.GetBytes(msg + "\r\n")); clientSocket.Close(); }
public static bool Authorize(string user, uint key) { try { Auth = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { Auth.Connect(Configs.SERVER_IP, Configs.AUTH_PORT); } catch { Console.WriteLine("Failed to send client data to game server"); } Auth.Send(System.Text.Encoding.ASCII.GetBytes("(A)" + user + "," + key)); Auth.Close(); } catch (SocketException e) { Console.WriteLine("Exception Caught while connecting to game server: " + e.ErrorCode.ToString()); return false; } return true; }
private bool Test_Port(string ipString, int port) { IPAddress ip = IPAddress.Parse(ipString); bool test = false; if (ipString.Contains(".")) { try { if (ipString.Contains(".")) { System.Net.Sockets.Socket s = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); s.Connect(ip, port); if (s.Connected == true) { test = true; s.Close(); } } } catch (SocketException) { test = false; } } return(test); }
public void Connect(EndPoint remoteEP) { #if !NO_UDT_CONNECTION //---- Tracing UDTTrace("UDTSocket[" + Handle + "]-Connect:" + remoteEP.ToString()); #if UDT_FULLTCP _tcpSocket.Connect(remoteEP); #else //---- UDT SocketAddress address = ((IPEndPoint)remoteEP).Serialize(); byte[] addressBuffer = new byte[address.Size]; for (int index = 0; index < address.Size; index++) { addressBuffer[index] = address[index]; } if (UDT_ERROR == API_UDTConnect(_handle, addressBuffer, address.Size)) { throw new UDTSocketException(); // Cannot connect } #endif #else throw new UDTSocketException(); // Cannot connect #endif }
private string GetResponseFromQuoteCache(string requestMessage) { var messageBytes = Encoding.ASCII.GetBytes(requestMessage); try { // Open a new socket var sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); sender.Connect(_quoteCacheHost, _quoteCachePort); // Send request int sentBytes = sender.Send(messageBytes); Log.DebugFormat(CultureInfo.InvariantCulture, "Sent {0} bytes over socket to \"{1}\" on port {2}.", sentBytes, _quoteCacheHost, _quoteCachePort); // Wait for response var responseBuffer = new byte[ResponseBufferSize]; int receivedBytes = sender.Receive(responseBuffer); Log.DebugFormat(CultureInfo.InvariantCulture, "Received {0} bytes over socket from \"{1}\" on port {2}.", receivedBytes, _quoteCacheHost, _quoteCachePort); // Return response as string return Encoding.ASCII.GetString(responseBuffer); } catch (Exception ex) { throw new QuoteException(String.Format(CultureInfo.InvariantCulture, "Encountered an error while trying to connect to the quote cache at \"{0}\" on port {1}.", _quoteCacheHost, _quoteCachePort), ex); } }
public BluetoothStream(BluetoothDevice btdev) { socket = new Socket((AddressFamily)32, SocketType.Stream, (ProtocolType)3); byte[] btAddress = btdev.Address; try { BluetoothEndPoint btep = new BluetoothEndPoint(btAddress, guid_spp); utils.ddump("connecting to " + btdev.AddressStr); socket.Connect(btep); utils.ddump("connected! Create networkstream..."); networkstream = new NetworkStream(socket, true); utils.ddump("starting threads..."); thSend = new Thread(new ThreadStart(sendThread)); thSend.Name = "SendThread"; thSend.IsBackground = true; thSend.Start(); utils.ddump("Thread started: " + thSend.Name + ", " + thSend.ManagedThreadId.ToString("x08")); thRecv = new Thread(new ThreadStart(recvThread)); thRecv.Name = "RecvThread"; thRecv.IsBackground = true; thRecv.Start(); utils.ddump("Thread started: " + thRecv.Name + ", " + thRecv.ManagedThreadId.ToString("x08")); } catch (Exception ex) { connected = false; utils.ddump("BluetoothStream init failed with " + ex.Message); } }
//:this(btAddress) public BluetoothStream(byte[] btAddress, string sPin) { _btAddress = btAddress; if (sPin != String.Empty && sPin != "") setPIN(btAddress, sPin); socket = new Socket((AddressFamily)32, SocketType.Stream, (ProtocolType)3); try { BluetoothEndPoint btep = new BluetoothEndPoint(btAddress, guid_spp); socket.Connect(btep); networkstream = new NetworkStream(socket, true); thSend = new Thread(new ThreadStart(sendThread)); thSend.Name = "SendThread"; thSend.Start(); utils.ddump("Thread started: " + thSend.Name + ", " + thSend.ManagedThreadId.ToString()); thRecv = new Thread(new ThreadStart(recvThread)); thRecv.Name = "RecvThread"; thRecv.Start(); utils.ddump("Thread started: " + thRecv.Name + ", " + thRecv.ManagedThreadId.ToString()); } catch (Exception ex) { connected = false; utils.ddump("BluetoothStream init failed with "+ex.Message); } }
public AirservClient(string Host, int port) { client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); client.Connect(Host, port); client.BeginReceive(Buffer, 0, Buffer.Length, SocketFlags.None, onBeginReceive, null); }
public static void Connect(string strIP,string strPort) { if (socketClient != null && socketClient.Connected) { log("服务器已连接!"); return; } string ip = strIP; string port = strPort; socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { socketClient.Connect(ip, int.Parse(port)); log("连接服务器成功:" + ip + port); Thread t = new Thread(do_read); t.IsBackground = true; t.Start(); } catch (Exception ex) { log("连接服务器失败!错误信息:" + ex.Message); } }
public bool link(int room){ if (socket != null) unlink();//断开之前的连接 socket=new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个socket string r =room.ToString(); try{ window.write("连接到"+r+"中..."); byte[] temp = Encoding.ASCII.GetBytes("{\"roomid\":"+r+ ",\"uid\":201510566613409}");//构造房间信息 socket.Connect("dm.live.bilibili.com", 788);//连接到弹幕服务器 //构造消息头 byte[] head = { 0x00, 0x00, 0x00, (byte)(0x31+r.Length), 0x00, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x01 }; socket.Send(head);//发送消息头 socket.Send(temp);//发送请求正文——房间信息 socket.Send(re);//这个本来应该是用来获取人数的,但是长期不发送服务器会断开连接,这里是为了防止这样的情况发生 if (!flag)//检查读弹幕线程是否在工作 { keeper = new Thread(keep_link); keeper.IsBackground = true; reader = new Thread(getdanmu); reader.IsBackground = true; reader.Start(); keeper.Start(); } window.write("连接成功"); } catch (InvalidCastException) { window.write("连接失败"); } return true; }
public void Connect() { byte[] bytes = new byte[1024]; IPAddress ip = IPAddress.Parse(sIp); IPEndPoint remoteEP = new IPEndPoint(ip, gate); sender = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp); try { sender.Connect(remoteEP); isConected = true; } catch (ArgumentNullException ane) { isConected = false; Console.WriteLine("ArgumentNullException : {0}", ane.ToString()); } catch (SocketException se) { isConected = false; Console.WriteLine("SocketException : {0}", se.ToString()); } catch (Exception e) { isConected = false; Console.WriteLine("Unexpected exception : {0}", e.ToString()); } }
/// <summary> /// 同步连接服务器 /// </summary> /// <returns></returns> public virtual bool ConnectSyn() { if (this.isConnection) { return(true); } IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(this.Ip), this.Port); System.Net.Sockets.Socket tempSocket = new System.Net.Sockets.Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp); tempSocket.ReceiveTimeout = 30000; try { tempSocket.Connect(ipe); } catch (Exception) { return(false); } if (tempSocket.Connected) { sock = tempSocket; this.isConnection = true; } return(isConnection); }
public mysocket() { string line, ip; int port; string[] splits; // config file read StreamReader sr = new StreamReader("server_config"); line = sr.ReadLine(); splits = line.Split(' '); ip = splits[2]; line = sr.ReadLine(); splits = line.Split(' '); port = Convert.ToInt16(splits[2]); s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); bool reconnect = true; while(reconnect){ try { s.Connect(ip, port); handshake(); reconnect = false; } catch (System.Net.Sockets.SocketException) { Console.WriteLine("try to connect again"); } } }
public void Connect() { System.Net.IPHostEntry hostIps = System.Net.Dns.GetHostEntry(host); connctHost = hostIps.AddressList[0]; #if TESTMODE System.Diagnostics.Debug.WriteLine("-------------------------------------"); System.Diagnostics.Debug.WriteLine("Dns back"); foreach (var tempIp in hostIps.AddressList) { System.Diagnostics.Debug.WriteLine(tempIp.ToString()); } System.Diagnostics.Debug.WriteLine("-------------------------------------"); #endif mySocket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //mySocket.NoDelay = true; IPEndPoint hostEndPoint = new IPEndPoint(connctHost, 443); mySocket.Connect(hostEndPoint); { //ThreadPool.QueueUserWorkItem(new WaitCallback(ReceviData), mySocket); //这里使用线程池将失去部分对线程的控制能力(创建及启动会自动被延迟) reciveThread = new Thread(new ParameterizedThreadStart(ReceviData)); reciveThread.IsBackground = true; reciveThread.Start(mySocket); } Console.WriteLine("connect ok"); }
/// <summary> /// 打开连接 /// </summary> public void Open() { UnityEngine.NetworkReachability state = UnityEngine.Application.internetReachability; if (state != UnityEngine.NetworkReachability.NotReachable) { _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { _socket.Connect(_host, _port); } catch { //socket.Dispose(); _socket = null; throw; } _netview = CreateThread(); _thread = new Thread(new ThreadStart(CheckReceive)); _thread.Start(); } }
protected static Mono.Unix.UnixEndPoint CreateEndPoint(string path) { if (path == null) { throw new ArgumentNullException("path"); } Mono.Unix.UnixEndPoint ep = new Mono.Unix.UnixEndPoint( path); if (System.IO.File.Exists(path)) { System.Net.Sockets.Socket conn = new System.Net.Sockets.Socket( System.Net.Sockets.AddressFamily.Unix, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.IP); try { conn.Connect(ep); conn.Close(); throw new InvalidOperationException( string.Format(CultureInfo.CurrentCulture, Strings.UnixSocket_AlreadyExists, path)); } catch (System.Net.Sockets.SocketException) { } System.IO.File.Delete(path); } return(ep); }
private static async void Reconnect() { _client2.Dispose(); _client2 = null; bool reconnected = false; while (!reconnected) { try { if (_client2 == null) { _client2 = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); } _client2.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), ModemPort)); reconnected = true; } catch (Exception ex) { await Task.Delay(10000); Console.WriteLine(ex); continue; } } Task.Run(() => { Process(); }); }
public Exception Connect() { try { _socket.Connect(Host, Port); } catch (Exception e) { return(e); } NetStream = new NetworkStream(_socket); if (HandShake()) { try { DataReceiveThread = new Thread(DataReceiveLoop) { IsBackground = true }; DataReceiveThread.Start(); Ping(); } catch (Exception e) { Info = e.Message; PingTimeStamp = 0; _socket.Disconnect(true); } } return(null); }
public void reConnect() { clientSocket.Close(); clientSocket = null; sendBuffer = new byte[1024];//Send buffer //c# automatic assigesd to 0 try { clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); System.Threading.Thread tt = new System.Threading.Thread(delegate() { try { clientSocket.Connect(ip, port); } catch (Exception ee) { //MessageBox.Show(ee.Message + "\r\n From:" + this); } }); tt.Start(); } catch (Exception e) { //MessageBox.Show(e.Message + "\r\n From:" + this); } }
public static void sendFile(string hostname, int port, string filepath) { FileInfo file = new FileInfo(filepath); Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Connect(hostname, port); int length = (int)file.Length; using(FileStream reader = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.None)) { //socket.Send(BitConverter.GetBytes(length)); string fileName = Path.GetFileName(filepath); Byte[] fn_bytes = Encoding.Default.GetBytes(fileName); socket.Send(Methods.i2b(fn_bytes.Length)); socket.Send(fn_bytes); socket.Send(Methods.i2b(length)); long send = 0L; ////Console.WriteLine("Sending file:" + fileName + ".Plz wait..."); byte[] buffer = new byte[BufferSize]; int read, sent; //断点发送 在这里判断设置reader.Position即可 while((read = reader.Read(buffer, 0, BufferSize)) !=0) { sent = 0; while((sent += socket.Send(buffer, sent, read, SocketFlags.None)) < read) { send += (long)sent; //Console.WriteLine("Sent " + send + "/" + length + ".");//进度 } } //Console.WriteLine("Send finish."); } }
private void showData(String Msg) { IPAddress dataIP = Dns.Resolve(clientIP).AddressList[0]; IPEndPoint dataHost = new IPEndPoint(dataIP, dataPort); //Dim CurThread As Thread try { //CurThread = System.Threading.Thread.CurrentThread() byte[] sendByte = Encoding.Default.GetBytes(Msg); // Establish data connection dataSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); dataSocket.Connect(dataHost); //SyncLock CurThread dataSocket.Send(sendByte, 0, sendByte.Length, SocketFlags.None); Console.WriteLine(Msg); dataSocket.Close(); //End SyncLock } catch (Exception ex) { Console.WriteLine(ex.StackTrace.ToString()); dataSocket.Close(); } }
private void button1_Click(object sender, EventArgs ev) { Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); s.Connect("192.168.16.170", 10000); byte[] buf; buf = new byte[] { 0x00,0x06,0x10,0x12,0x00,0x00 }; s.Send(buf); byte[] rec=new byte[128]; int r = 0; s.ReceiveTimeout = 1000; try { r = s.Receive(rec); Debug.WriteLine(FUNC.BytesToString(rec, 0, r)); r = s.Receive(rec); Debug.WriteLine(FUNC.BytesToString(rec, 0, r)); } catch (Exception e) { Debug.WriteLine(e.Message); } s.Disconnect(false); }
private static Socket ConnectSocket(string server, int port) { Socket s = null; IPHostEntry hostEntry = null; // Get host related information. hostEntry = Dns.GetHostEntry(server); // Loop through the AddressList to obtain the supported AddressFamily. This is to avoid // an exception that occurs when the host IP Address is not compatible with the address family // (typical in the IPv6 case). foreach (IPAddress address in hostEntry.AddressList) { IPEndPoint ipe = new IPEndPoint(address, port); System.Net.Sockets.Socket tempSocket = new System.Net.Sockets.Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp); tempSocket.Connect(ipe); if (tempSocket.Connected) { s = tempSocket; break; } else { continue; } } return(s); }
/// <summary> This method opens a socket connection to the specified server.</summary> /// <returns> The return value is a string of the response from the server.</returns> public void Connect() { if (_connInfo == null) { throw new Exception("The SocketConnectionInfo class is null this is mandatory field."); } if (_connInfo.SocketProtocolType != ProtocolType.Tcp && _connInfo.IsTelnet) { throw new Exception("If you want to use the Telnet Protocol you must set your ProtocolType to \"TCP\"."); } if (_connInfo.IPVersion == IpVersionType.IPv6 && !System.Net.Sockets.Socket.OSSupportsIPv6) { throw new Exception("Your system does not support IPv6\r\n" + "Check you have IPv6 enabled and have changed machine.config"); } // Create a TCP/IP socket. _socket = new System.Net.Sockets.Socket(_connInfo.IPVersion == IpVersionType.IPv6 ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork, _connInfo.SocketType, _connInfo.SocketProtocolType); //Connect _socket.Connect(_connInfo.IpEndPoint); //Store the cocket info once connected. _connInfo.Socket = _socket; _buffer = new byte[1024]; _receivedData = ""; _socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(OnDataReceived), null); }
/// <summary> /// Connects the specified host. /// </summary> /// <param name="host">The host.</param> /// <param name="port">The port.</param> public void Connect(string host, int port) { try { if (Connected) { return; } SetHost(host); SetPort(port); // Make our socket socket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Connect that shit up socket.Connect(Host, Port); listener?.Stop(); listener = new Listener(this, socket, Listener.ListenerType.Client); SetOnConnectedFun(); } catch (Exception ex) { Log.Error("Socket", ex.Message); } }
public ClientSocket Connect(string address, int port) { _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _socket.Connect(address, port); _socketInfo = new SocketInfo(_socket); return this; }
public TempSocket() { if (!Connection.IsConnected) { return; } try { TcpClient = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) { ReceiveBufferSize = 50 * 1024, SendBufferSize = 50 * 1024, }; TcpClient.Connect(Connection.TcpClient.RemoteEndPoint.ToString().Split(':')[0], Convert.ToInt32(Connection.TcpClient.RemoteEndPoint.ToString().Split(':')[1])); Debug.WriteLine("Temp Connected!"); IsConnected = true; SslClient = new SslStream(new NetworkStream(TcpClient, true), false, ValidateServerCertificate); SslClient.AuthenticateAsClient(TcpClient.RemoteEndPoint.ToString().Split(':')[0], null, SslProtocols.Tls, false); Buffer = new byte[4]; MS = new MemoryStream(); Tick = new Timer(new TimerCallback(CheckServer), null, new Random().Next(15 * 1000, 30 * 1000), new Random().Next(15 * 1000, 30 * 1000)); SslClient.BeginRead(Buffer, 0, Buffer.Length, ReadServertData, null); } catch { Debug.WriteLine("Temp Disconnected!"); Dispose(); IsConnected = false; } }
protected WebServerSocketRequest ConnectAndGetWebServerRequest(ushort requestId) { var sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); sock.Connect(ListenOn, ListenPort); return new WebServerSocketRequest(sock, requestId); }
private static Socket CreateConnectSocket() { Logging.WriteLog("Creating pooled socket"); var sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); sock.Connect(address, port); return sock; }
private static bool PostAction(Proxy p, Server server, Action action) { var instance = p.Instance; // if we can't issue any commands, bomb out if (instance.AdminUser.IsNullOrEmpty() || instance.AdminPassword.IsNullOrEmpty()) return false; var loginInfo = instance.AdminUser + ":" + instance.AdminPassword; var haproxyUri = new Uri(instance.Url); var requestBody = string.Format("s={0}&action={1}&b={2}", server.Name, action.ToString().ToLower(), p.Name); var requestHeader = string.Format("POST {0} HTTP/1.1\r\nHost: {1}\r\nContent-Length: {2}\r\nAuthorization: Basic {3}\r\n\r\n", haproxyUri.AbsolutePath, haproxyUri.Host, Encoding.GetEncoding("ISO-8859-1").GetBytes(requestBody).Length, Convert.ToBase64String(Encoding.Default.GetBytes(loginInfo))); try { var socket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Connect(haproxyUri.Host, haproxyUri.Port); socket.Send(Encoding.UTF8.GetBytes(requestHeader + requestBody)); var responseBytes = new byte[socket.ReceiveBufferSize]; socket.Receive(responseBytes); var response = Encoding.UTF8.GetString(responseBytes); instance.PurgeCache(); return response.StartsWith("HTTP/1.0 303") || response.StartsWith("HTTP/1.1 303"); } catch (Exception e) { Current.LogException(e); return false; } }
public void TestStream(string urlStr) { // Make a simple HTTP request var url = new Uri(urlStr); var socket = new Socket(SocketType.Stream, ProtocolType.Tcp); socket.Connect(url.Host, url.Port); using (var stream = GetStream(socket, url)) { // Send the request var request = $"GET {url.PathAndQuery} HTTP/1.1\r\nHost: {url.Host}\r\nConnection: close\r\n\r\n"; var buffer = Encoding.UTF8.GetBytes(request); stream.Write(buffer, 0, buffer.Length); // Read the response byte[] readbuffer = new byte[1024]; int read = 0; Console.WriteLine("Response:"); while((read = stream.Read(readbuffer, 0, readbuffer.Length)) != 0) { var converted = Encoding.UTF8.GetString(readbuffer, 0, read); Console.Write(converted); } } }
public bool SendData(string textdata) { if (string.IsNullOrEmpty(textdata)) { return(false); } if (textdata.Trim().ToLower() == "exit") { return(true); } // The chat client always starts up on the localhost, using the default port IPHostEntry hostInfo = Dns.GetHostByName(DEFAULT_SERVER); IPAddress serverAddr = hostInfo.AddressList[0]; var clientEndPoint = new IPEndPoint(serverAddr, DEFAULT_PORT); // Create a listener socket and bind it to the endpoint clientSocket = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp); clientSocket.Connect(clientEndPoint); byte[] byData = System.Text.Encoding.ASCII.GetBytes(textdata); clientSocket.Send(byData); clientSocket.Close(); return(false); }
private bool Connect(string ip, int port) { try { if (port == 0 || ip == "") { return(false); } Debug.Log("connect battle server " + ip + ":" + port); IPAddress ipAddress; AddressFamily af; bool ok = Misc.Utils.IPV4ToIPV6(ip, out ipAddress, out af); this.TryCloseSocket(); _inner_socket = new Socket(af, System.Net.Sockets.SocketType.Stream, ProtocolType.Tcp); _inner_socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true); _inner_socket.Connect(new IPEndPoint(ipAddress, port)); _inner_socket.Blocking = true; _inner_socket.NoDelay = true; _inner_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, 1024 * 16); _inner_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, 1024 * 16); this.isConnected = true; } catch (Exception e) { this.isConnected = false; _inner_socket = null; Debug.Log(e.Message); return(false); } return(true); }
public CSocket(IPEndPoint _endPoint, SocketPool _pool, SocketPoolProfile config) { socketConfig = config; endpoint = _endPoint; pool = _pool; System.Net.Sockets.Socket _socket = new System.Net.Sockets.Socket(_endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, (int)config.SendTimeout.TotalMilliseconds); _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 24 * 3600 * 1000 /*one day*/);//(int)config.ReceiveTimeout.TotalMilliseconds); _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, !config.Nagle); _socket.Connect(_endPoint); socket = _socket; this.inputStream = new BufferedStream(new NetworkStream(this.socket), config.BufferSize); Thread th = new Thread(delegate() { while (true) { try { Receive(); } catch (Exception ex) { logger.Notice(ex.Message); } } }); th.Start(); }
/// <summary> /// Bluetooth への接続処理を実行する /// </summary> /// <remarks> /// リトライの仕組み実装しておくこと /// </remarks> public void Connection() { try { if (null == conn) { // 指定されたサーバに接続 Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); sock.Connect(ipAddress, SOCKET_PORT); conn = new NetworkStream(sock, true); btReceiver = new BluetoothReceiver(conn); btSender = new BluetoothSender(conn); btReceiver.ReceiverStart(); } } catch (SocketException e) { // リトライ? // _logger.ErrorException("SocketException", e); // Console.Out.WriteLine("caught an exception: {0}", e.Message); } catch (Exception e) { // _logger.ErrorException("Error", e); // Console.Out.WriteLine("caught an exception: {0}", e.Message); throw; } return ; }
protected static Mono.Unix.UnixEndPoint CreateEndPoint (string path) { if (path == null) throw new ArgumentNullException ("path"); Mono.Unix.UnixEndPoint ep = new Mono.Unix.UnixEndPoint ( path); if (System.IO.File.Exists (path)) { System.Net.Sockets.Socket conn = new System.Net.Sockets.Socket ( System.Net.Sockets.AddressFamily.Unix, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.IP); try { conn.Connect (ep); conn.Close (); throw new InvalidOperationException ( string.Format (CultureInfo.CurrentCulture, Strings.UnixSocket_AlreadyExists, path)); } catch (System.Net.Sockets.SocketException) { } System.IO.File.Delete (path); } return ep; }
public CSocket(IPEndPoint _endPoint, SocketPool _pool, SocketPoolProfile config) { socketConfig = config; endpoint = _endPoint; pool = _pool; System.Net.Sockets.Socket _socket = new System.Net.Sockets.Socket(_endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, (int)config.SendTimeout.TotalMilliseconds); _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 24 * 3600 * 1000/*one day*/);//(int)config.ReceiveTimeout.TotalMilliseconds); _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, !config.Nagle); _socket.Connect(_endPoint); socket = _socket; this.inputStream = new BufferedStream(new NetworkStream(this.socket), config.BufferSize); Thread th = new Thread(delegate() { while (true) { try { Receive(); } catch (Exception ex) { logger.Notice(ex.Message); } } }); th.Start(); }
public void cidClient(String callcenter_idx, FormBegin begin) { this.callcenter_idx = callcenter_idx; this.begin = begin; int port = 54321; try { // get user input and transmit it to server socket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse("110.10.189.101"); //System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse("127.0.0.1"); System.Net.IPEndPoint remoteEP = new System.Net.IPEndPoint(ipAdd, 54321); socket.Connect(remoteEP); //Async Read form the server side Receive(socket); socket.Send(encoding.GetBytes("start_begin_callcenter:" + callcenter_idx)); byte[] Serbyte = new byte[30]; } catch (System.IO.IOException e) { System.Console.Out.WriteLine(e); } }
/// <summary> /// 连接到远程端 /// </summary> /// <param name="remoteEndPoint">远程端</param> /// <exception cref="ArgumentNullException"></exception> /// <returns></returns> private SocketError ConnectInternal(EndPoint remoteEndPoint) { if (remoteEndPoint == null) { throw new ArgumentNullException(); } if (this.IsConnected == true) { return(SocketError.IsConnected); } var addressFamily = AddressFamily.InterNetwork; if (remoteEndPoint.AddressFamily != AddressFamily.Unspecified) { addressFamily = remoteEndPoint.AddressFamily; } var socket = new System.Net.Sockets.Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp); try { socket.Connect(remoteEndPoint); this.session.SetSocket(socket); this.session.SetKeepAlive(this.KeepAlivePeriod); return(SocketError.Success); } catch (SocketException ex) { socket.Dispose(); return(ex.SocketErrorCode); } }
public GDBDebugger() { string gdbHost = Application.Session.Properties["GDBDebugger.Host"]; int gdbPort = int.Parse(Application.Session.Properties["GDBDebugger.Port"]); // Initialise locals this.breakpoints = new List<Breakpoint>(); // Set the current architecture to the session one this.CurrentArchitecture = Application.Session.Architecture; // Connect to GDB stub var sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP); sock.Connect(gdbHost, gdbPort); // Make empty initial register listing this.Registers = new RegisterSet(new Register[0], new bool[0], new bool[0]); // Create connector and begin debugging this.connector = new GDBConnector(sock); try { this.connector.EstablishConnection(); this.CurrentStatus = DebugStatus.Suspended; this.connector.Paused += OnGDBPaused; } catch { this.CurrentStatus = DebugStatus.Disconnected; this.connector.Dispose(); throw; } }
public bool SendCmdRequest(CmdRequest request) { Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { socket.Connect("127.0.0.1", Port); using (NetworkStream stream = new NetworkStream(socket)) { using (BsonWriter writer = new BsonWriter(stream)) { JsonSerializer serializer = new JsonSerializer(); serializer.Serialize(writer, request); writer.Flush(); writer.Close(); } stream.Close(); } } catch(Exception ex) { Logger.AddError(string.Format("Failed to send cmd request to checker with port = {0}", Port), ex); return false; } return true; }
public System.Net.Sockets.Socket GetConnection(string server, int port) { System.Net.Sockets.Socket s = null; IPHostEntry hostEntry = null; hostEntry = Dns.GetHostEntry(server); foreach (IPAddress address in hostEntry.AddressList) { IPEndPoint ipe = new IPEndPoint(address, port); System.Net.Sockets.Socket tempSocket = new System.Net.Sockets.Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp); tempSocket.Connect(ipe); if (tempSocket.Connected) { s = tempSocket; break; } else { continue; } } return(s); }
public byte[] sendBuffer = null;//Send buffer public socket(String ipAddress) { ip = ipAddress; sendBuffer = new byte[1024];//Send buffer //c# automatic assigesd to 0 try { //创建一个Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); System.Threading.Thread tt = new System.Threading.Thread(delegate() { //连接到指定服务器的指定端口 //方法参考:http://msdn.microsoft.com/zh-cn/library/system.net.sockets.socket.connect.aspx try { clientSocket.Connect(ip, port); } catch(Exception ee) { MessageBox.Show(ee.Message); } }); tt.Start(); } catch (Exception e) { MessageBox.Show(e.Message + "\r\n From:" + this); } }
public HttpDownloadStreamSync(string url) { var host = url.Substring(7, url.Length - 7); host = host.Substring(0, host.IndexOf("/", StringComparison.Ordinal)); socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) { NoDelay = true }; socket.Connect(host, 80); while (!socket.Connected) Thread.Sleep(1); var request = string.Format("GET {0} HTTP/1.1\r\nHost: {0}\r\nConnection: Keep-Alive{1}", url, HeaderEnd); socket.Send(Encoding.Default.GetBytes(request)); using (var stream = new MemoryStream()) { int bytesReceived; var buffer = new byte[1]; var response = string.Empty; while ((bytesReceived = socket.Receive(buffer)) > 0 && !response.EndsWith(HeaderEnd)) { stream.Write(buffer, 0, bytesReceived); response = Encoding.Default.GetString(stream.ToArray()).ToLower(CultureInfo.InvariantCulture); } var responseHeader = response.Substring(0, response.IndexOf(HeaderEnd, StringComparison.Ordinal)); var headers = responseHeader.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); contentLength = Convert.ToInt32(headers.First(c => c.Contains("content-length")).Split(':')[1].Trim()); } }
public bool initializeConnection() { try { m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); m_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true); m_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); m_socket.SendTimeout = 5000; m_socket.ReceiveTimeout = 5000; m_frm.Print("Connecting to " + ECCServerIP + " at port " + ECCServerPort + " ..."); m_socket.Connect(ECCServerIP, Convert.ToInt32(ECCServerPort)); } catch (Exception ex) { m_frm.Print("Error!Failed to connect to ECC server!" + ex.Message); return false; } if (!Authenticate()) return false; return true; }
/// <summary> /// /// </summary> private void TryConnect() { while (true) { try { mIsConnecting = true; Thread.Sleep(mData.ReTryDuration); try { if (mClient.Connected) { break; } mClient = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp); mClient.Connect(System.Net.IPAddress.Parse(mData.ServerIp), mData.Port); if (mClient.Connected) { break; } } catch { } } catch { } } mIsConnecting = false; }
private string GetRightIp() { try { using (var s = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { s.Bind(new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0)); s.Connect("google.com", 0); var ipaddr = s.LocalEndPoint as System.Net.IPEndPoint; return(ipaddr.Address.ToString()); } } catch (Exception ex) { var host = Dns.GetHostEntry(Dns.GetHostName()); foreach (var ip in host.AddressList) { if (ip.AddressFamily == AddressFamily.InterNetwork) { return(ip.ToString()); } } throw new Exception("No network adapters with an IPv4 address in the system!"); } }
static void Start() { var socket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); //var ip = new IPAddress(new byte[] { 192, 168, 1, 87 }); var endPoint = new IPEndPoint(IPAddress.Any, MAPLE_SERVER_BROADCASTPORT); socket.Connect(endPoint); //byte[] bytesToSend = Encoding.UTF8.GetBytes(msg); while (true) { //socket.SendTo(bytesToSend, bytesToSend.Length, SocketFlags.None, endPoint); while (socket.Poll(2000000, SelectMode.SelectRead)) { if (socket.Available > 0) { byte[] inBuf = new byte[socket.Available]; EndPoint recEndPoint = new IPEndPoint(IPAddress.Any, 0); socket.ReceiveFrom(inBuf, ref recEndPoint); //if (!recEndPoint.Equals(endPoint))// Check if the received packet is from the 192.168.0.2 // continue; Debug.WriteLine(new String(Encoding.UTF8.GetChars(inBuf))); } } Thread.Sleep(100); } }
private void showData(string data) { try { IPAddress dataIP = Dns.Resolve(clientIP).AddressList[0]; IPEndPoint dataHost = new IPEndPoint(dataIP, dataPort); byte[] sendByte = Encoding.Default.GetBytes(data); // 建立 Data Socket dataSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // 建立用戶端與伺服端連線 dataSocket.Connect(dataHost); // 傳送資料至已連線的伺服端 int bytesSend = dataSocket.Send(sendByte, 0, sendByte.Length, SocketFlags.None); Console.WriteLine(data); dataSocket.Close(); } catch (Exception ex) { Console.WriteLine(ex.StackTrace.ToString()); if (dataSocket.Connected) { dataSocket.Close(); } } }
public void SentMessage(ServerFunctionsNames serverFunctionName, object data = null, string UserName = "******") { clientSocket = new Sockets.Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); try { clientSocket.Connect(remoteEndPoint); var buffer = new byte[2048]; byte[] messageData = Serializer.Serialize(new SocketMessage(serverFunctionName.ToString(), UserName, data)); var messageSize = BitConverter.GetBytes(messageData.Count() + 4); var message = messageSize.Concat(messageData).ToArray(); clientSocket.Send(message); var recievedBytesCount = clientSocket.Receive(buffer); var recievedMessage = Serializer.Deserialize <SocketMessage>(buffer); ReflectionHelper.InvokeFunction(clientController, recievedMessage.CallbackFunction, new object[] { recievedMessage.Data }); clientSocket.Shutdown(SocketShutdown.Both); clientSocket.Close(); } catch (Exception ex) { throw new Exception("Failed to send message to serwer"); } }
public static void Start_Client(System.Net.Sockets.Socket socket, IPEndPoint remoteEP) { // Data buffer byte[] bytes = new byte[1024]; // Connect to a server try { socket.Connect(remoteEP); status_label.Text = "connected"; // Receive data int bytesRec = socket.Receive(bytes); console_text.Buffer.Text = Encoding.ASCII.GetString(bytes, 0, bytesRec); socket.Shutdown(SocketShutdown.Both); socket.Close(); status_label.Text = "disconnected"; } catch (ArgumentNullException ane) { console_text.Buffer.Text = ane.ToString(); } catch (SocketException se) { console_text.Buffer.Text = se.ToString(); } catch (Exception e) { console_text.Buffer.Text = e.ToString(); } }
private static bool PostAction(Proxy p, Server server, Action action) { var instance = p.Instance; // if we can't issue any commands, bomb out if (instance.AdminUser.IsNullOrEmpty() || instance.AdminPassword.IsNullOrEmpty()) { return(false); } var loginInfo = $"{instance.AdminUser}:{instance.AdminPassword}"; var haproxyUri = new Uri(instance.Url); var requestBody = $"s={server.Name}&action={action.ToString().ToLower()}&b={p.Name}"; var requestHeader = $"POST {haproxyUri.AbsolutePath} HTTP/1.1\r\nHost: {haproxyUri.Host}\r\nContent-Length: {Encoding.GetEncoding("ISO-8859-1").GetBytes(requestBody).Length}\r\nAuthorization: Basic {Convert.ToBase64String(Encoding.Default.GetBytes(loginInfo))}\r\n\r\n"; try { var socket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Connect(haproxyUri.Host, haproxyUri.Port); socket.Send(Encoding.UTF8.GetBytes(requestHeader + requestBody)); var responseBytes = new byte[socket.ReceiveBufferSize]; socket.Receive(responseBytes); var response = Encoding.UTF8.GetString(responseBytes); instance.PurgeCache(); return(response.StartsWith("HTTP/1.0 303") || response.StartsWith("HTTP/1.1 303")); } catch (Exception e) { Current.LogException(e); return(false); } }
private void btnStartMulti_Click(object sender, EventArgs e) { btnStopMulti_Click(this, EventArgs.Empty); _isMultiStart = true; var ipEndPoint = new IPEndPoint(IPAddress.Parse(txtMultiIp.Text), int.Parse(txtMultiPort.Text)); var threadCount = int.Parse(txtMultiThreadCount.Text); for (var i = 0; i < threadCount; i++) { Task.Factory.StartNew(() => { while (_isMultiStart) { var socket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { _socketList.Add(socket); socket.Connect(ipEndPoint); socket.Close(); } catch (Exception) { } finally { _socketList.Remove(socket); } } }); } }
public static void initConnection(int portNumber) { System.String server = "nt126101"; System.String lineToBeSent; System.IO.StreamReader input; System.IO.StreamWriter output; int ERROR = 1; System.Console.Out.WriteLine("server port = 1500 (default)"); try { //UPGRADE_TODO: Expected value of parameters of constructor 'java.io.BufferedReader.BufferedReader' are different in the equivalent in .NET. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1092"' //UPGRADE_ISSUE: 'java.lang.System.in' was converted to 'System.Console.In' which is not valid in this expression. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1109"' // input = new System.IO.StreamReader(new System.IO.StreamReader(System.Console.In).BaseStream, System.Text.Encoding.UTF7); // System.IO.StreamWriter temp_writer; // temp_writer = new System.IO.StreamWriter((System.IO.Stream) socket.GetStream()); // temp_writer.AutoFlush = true; // output = temp_writer; // get user input and transmit it to server socket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse("127.0.0.1"); System.Net.IPEndPoint remoteEP = new System.Net.IPEndPoint(ipAdd, portNumber); socket.Connect(remoteEP); //Async Read form the server side! Receive(socket); //new System.Net.Sockets.TcpClient(server, port); while (true) { lineToBeSent = System.Console.ReadLine(); // stop if input line is "." if (lineToBeSent.Equals(".")) { socket.Close(); break; } lineToBeSent += "\n"; //output.WriteLine(lineToBeSent);\ //System.Net.Sockets.NetworkStream tempstream = socket.GetStream(); Send(lineToBeSent); } byte[] Serbyte = new byte[30]; // socket.Receive(Serbyte,0,20,System.Net.Sockets.SocketFlags.None); // System.Console.WriteLine("Message from server \n" + encoding.GetString(Serbyte)); //socket.Close(); } catch (System.IO.IOException e) { System.Console.Out.WriteLine(e); } }
public void Send(string filePath) { if (string.IsNullOrEmpty(filePath)) filePath = GetFileName(); var fileInfo = new FileInfo(filePath); var fName = fileInfo.Name; var clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); byte[] fileName = Encoding.UTF8.GetBytes(fName); //file name //byte[] fileData = File.ReadAllBytes(filePath); //file byte[] fileNameLen = BitConverter.GetBytes(fileName.Length); //lenght of file name //var clientData = new byte[4 + fileName.Length + fileData.Length]; var clientData = new byte[4 + fileName.Length]; fileNameLen.CopyTo(clientData, 0); fileName.CopyTo(clientData, 4); //fileData.CopyTo(clientData, 4 + fileName.Length); clientSocket.Connect("127.0.0.1", 9050); //target machine's ip address and the port number //Connection.Send(clientData); clientSocket.SendFile(filePath, clientData, null, TransmitFileOptions.WriteBehind); clientSocket.Close(); }